System.Data.SQLite
Check-in [0df515ab41]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Update SQLite core library to the latest trunk code.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 0df515ab41770c6283b6e04b2e13bd2701b77ee5
User & Date: mistachkin 2013-10-12 21:24:20
Context
2013-10-15
06:26
Update SQLite core library to the latest trunk code. Add the 'totype' extension. check-in: 159d24c754 user: mistachkin tags: trunk
2013-10-12
21:24
Update SQLite core library to the latest trunk code. check-in: 0df515ab41 user: mistachkin tags: trunk
2013-10-07
18:22
Fix data table name issue for the GetSchema method reported on the mailing list. check-in: e1c3a2bc9c user: mistachkin tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to SQLite.Interop/src/core/sqlite3.c.

    21     21   #define SQLITE_AMALGAMATION 1
    22     22   #ifndef SQLITE_PRIVATE
    23     23   # define SQLITE_PRIVATE static
    24     24   #endif
    25     25   #ifndef SQLITE_API
    26     26   # define SQLITE_API
    27     27   #endif
    28         -/************** Begin file sqliteInt.h ***************************************/
    29         -/*
    30         -** 2001 September 15
    31         -**
    32         -** The author disclaims copyright to this source code.  In place of
    33         -** a legal notice, here is a blessing:
    34         -**
    35         -**    May you do good and not evil.
    36         -**    May you find forgiveness for yourself and forgive others.
    37         -**    May you share freely, never taking more than you give.
    38         -**
    39         -*************************************************************************
    40         -** Internal interface definitions for SQLite.
    41         -**
    42         -*/
    43         -#ifndef _SQLITEINT_H_
    44         -#define _SQLITEINT_H_
    45         -
    46         -/*
    47         -** These #defines should enable >2GB file support on POSIX if the
    48         -** underlying operating system supports it.  If the OS lacks
    49         -** large file support, or if the OS is windows, these should be no-ops.
    50         -**
    51         -** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
    52         -** system #includes.  Hence, this block of code must be the very first
    53         -** code in all source files.
    54         -**
    55         -** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
    56         -** on the compiler command line.  This is necessary if you are compiling
    57         -** on a recent machine (ex: Red Hat 7.2) but you want your code to work
    58         -** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
    59         -** without this option, LFS is enable.  But LFS does not exist in the kernel
    60         -** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
    61         -** portability you should omit LFS.
    62         -**
    63         -** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
    64         -*/
    65         -#ifndef SQLITE_DISABLE_LFS
    66         -# define _LARGE_FILE       1
    67         -# ifndef _FILE_OFFSET_BITS
    68         -#   define _FILE_OFFSET_BITS 64
    69         -# endif
    70         -# define _LARGEFILE_SOURCE 1
    71         -#endif
    72         -
    73         -/*
    74         -** Include the configuration header output by 'configure' if we're using the
    75         -** autoconf-based build
    76         -*/
    77         -#ifdef _HAVE_SQLITE_CONFIG_H
    78         -#include "config.h"
    79         -#endif
    80         -
    81         -/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
    82         -/************** Begin file sqliteLimit.h *************************************/
    83         -/*
    84         -** 2007 May 7
    85         -**
    86         -** The author disclaims copyright to this source code.  In place of
    87         -** a legal notice, here is a blessing:
    88         -**
    89         -**    May you do good and not evil.
    90         -**    May you find forgiveness for yourself and forgive others.
    91         -**    May you share freely, never taking more than you give.
    92         -**
    93         -*************************************************************************
    94         -** 
    95         -** This file defines various limits of what SQLite can process.
    96         -*/
    97         -
    98         -/*
    99         -** The maximum length of a TEXT or BLOB in bytes.   This also
   100         -** limits the size of a row in a table or index.
   101         -**
   102         -** The hard limit is the ability of a 32-bit signed integer
   103         -** to count the size: 2^31-1 or 2147483647.
   104         -*/
   105         -#ifndef SQLITE_MAX_LENGTH
   106         -# define SQLITE_MAX_LENGTH 1000000000
   107         -#endif
   108         -
   109         -/*
   110         -** This is the maximum number of
   111         -**
   112         -**    * Columns in a table
   113         -**    * Columns in an index
   114         -**    * Columns in a view
   115         -**    * Terms in the SET clause of an UPDATE statement
   116         -**    * Terms in the result set of a SELECT statement
   117         -**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
   118         -**    * Terms in the VALUES clause of an INSERT statement
   119         -**
   120         -** The hard upper limit here is 32676.  Most database people will
   121         -** tell you that in a well-normalized database, you usually should
   122         -** not have more than a dozen or so columns in any table.  And if
   123         -** that is the case, there is no point in having more than a few
   124         -** dozen values in any of the other situations described above.
   125         -*/
   126         -#ifndef SQLITE_MAX_COLUMN
   127         -# define SQLITE_MAX_COLUMN 2000
   128         -#endif
   129         -
   130         -/*
   131         -** The maximum length of a single SQL statement in bytes.
   132         -**
   133         -** It used to be the case that setting this value to zero would
   134         -** turn the limit off.  That is no longer true.  It is not possible
   135         -** to turn this limit off.
   136         -*/
   137         -#ifndef SQLITE_MAX_SQL_LENGTH
   138         -# define SQLITE_MAX_SQL_LENGTH 1000000000
   139         -#endif
   140         -
   141         -/*
   142         -** The maximum depth of an expression tree. This is limited to 
   143         -** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
   144         -** want to place more severe limits on the complexity of an 
   145         -** expression.
   146         -**
   147         -** A value of 0 used to mean that the limit was not enforced.
   148         -** But that is no longer true.  The limit is now strictly enforced
   149         -** at all times.
   150         -*/
   151         -#ifndef SQLITE_MAX_EXPR_DEPTH
   152         -# define SQLITE_MAX_EXPR_DEPTH 1000
   153         -#endif
   154         -
   155         -/*
   156         -** The maximum number of terms in a compound SELECT statement.
   157         -** The code generator for compound SELECT statements does one
   158         -** level of recursion for each term.  A stack overflow can result
   159         -** if the number of terms is too large.  In practice, most SQL
   160         -** never has more than 3 or 4 terms.  Use a value of 0 to disable
   161         -** any limit on the number of terms in a compount SELECT.
   162         -*/
   163         -#ifndef SQLITE_MAX_COMPOUND_SELECT
   164         -# define SQLITE_MAX_COMPOUND_SELECT 500
   165         -#endif
   166         -
   167         -/*
   168         -** The maximum number of opcodes in a VDBE program.
   169         -** Not currently enforced.
   170         -*/
   171         -#ifndef SQLITE_MAX_VDBE_OP
   172         -# define SQLITE_MAX_VDBE_OP 25000
   173         -#endif
   174         -
   175         -/*
   176         -** The maximum number of arguments to an SQL function.
   177         -*/
   178         -#ifndef SQLITE_MAX_FUNCTION_ARG
   179         -# define SQLITE_MAX_FUNCTION_ARG 127
   180         -#endif
   181         -
   182         -/*
   183         -** The maximum number of in-memory pages to use for the main database
   184         -** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
   185         -*/
   186         -#ifndef SQLITE_DEFAULT_CACHE_SIZE
   187         -# define SQLITE_DEFAULT_CACHE_SIZE  2000
   188         -#endif
   189         -#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
   190         -# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
   191         -#endif
   192         -
   193         -/*
   194         -** The default number of frames to accumulate in the log file before
   195         -** checkpointing the database in WAL mode.
   196         -*/
   197         -#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
   198         -# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
   199         -#endif
   200         -
   201         -/*
   202         -** The maximum number of attached databases.  This must be between 0
   203         -** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
   204         -** is used internally to track attached databases.
   205         -*/
   206         -#ifndef SQLITE_MAX_ATTACHED
   207         -# define SQLITE_MAX_ATTACHED 10
   208         -#endif
   209         -
   210         -
   211         -/*
   212         -** The maximum value of a ?nnn wildcard that the parser will accept.
   213         -*/
   214         -#ifndef SQLITE_MAX_VARIABLE_NUMBER
   215         -# define SQLITE_MAX_VARIABLE_NUMBER 999
   216         -#endif
   217         -
   218         -/* Maximum page size.  The upper bound on this value is 65536.  This a limit
   219         -** imposed by the use of 16-bit offsets within each page.
   220         -**
   221         -** Earlier versions of SQLite allowed the user to change this value at
   222         -** compile time. This is no longer permitted, on the grounds that it creates
   223         -** a library that is technically incompatible with an SQLite library 
   224         -** compiled with a different limit. If a process operating on a database 
   225         -** with a page-size of 65536 bytes crashes, then an instance of SQLite 
   226         -** compiled with the default page-size limit will not be able to rollback 
   227         -** the aborted transaction. This could lead to database corruption.
   228         -*/
   229         -#ifdef SQLITE_MAX_PAGE_SIZE
   230         -# undef SQLITE_MAX_PAGE_SIZE
   231         -#endif
   232         -#define SQLITE_MAX_PAGE_SIZE 65536
   233         -
   234         -
   235         -/*
   236         -** The default size of a database page.
   237         -*/
   238         -#ifndef SQLITE_DEFAULT_PAGE_SIZE
   239         -# define SQLITE_DEFAULT_PAGE_SIZE 1024
   240         -#endif
   241         -#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
   242         -# undef SQLITE_DEFAULT_PAGE_SIZE
   243         -# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
   244         -#endif
   245         -
   246         -/*
   247         -** Ordinarily, if no value is explicitly provided, SQLite creates databases
   248         -** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
   249         -** device characteristics (sector-size and atomic write() support),
   250         -** SQLite may choose a larger value. This constant is the maximum value
   251         -** SQLite will choose on its own.
   252         -*/
   253         -#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
   254         -# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
   255         -#endif
   256         -#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
   257         -# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
   258         -# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
   259         -#endif
   260         -
   261         -
   262         -/*
   263         -** Maximum number of pages in one database file.
   264         -**
   265         -** This is really just the default value for the max_page_count pragma.
   266         -** This value can be lowered (or raised) at run-time using that the
   267         -** max_page_count macro.
   268         -*/
   269         -#ifndef SQLITE_MAX_PAGE_COUNT
   270         -# define SQLITE_MAX_PAGE_COUNT 1073741823
   271         -#endif
   272         -
   273         -/*
   274         -** Maximum length (in bytes) of the pattern in a LIKE or GLOB
   275         -** operator.
   276         -*/
   277         -#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
   278         -# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
   279         -#endif
   280         -
   281         -/*
   282         -** Maximum depth of recursion for triggers.
   283         -**
   284         -** A value of 1 means that a trigger program will not be able to itself
   285         -** fire any triggers. A value of 0 means that no trigger programs at all 
   286         -** may be executed.
   287         -*/
   288         -#ifndef SQLITE_MAX_TRIGGER_DEPTH
   289         -# define SQLITE_MAX_TRIGGER_DEPTH 1000
   290         -#endif
   291         -
   292         -/************** End of sqliteLimit.h *****************************************/
   293         -/************** Continuing where we left off in sqliteInt.h ******************/
   294         -
   295         -/* Disable nuisance warnings on Borland compilers */
   296         -#if defined(__BORLANDC__)
   297         -#pragma warn -rch /* unreachable code */
   298         -#pragma warn -ccc /* Condition is always true or false */
   299         -#pragma warn -aus /* Assigned value is never used */
   300         -#pragma warn -csu /* Comparing signed and unsigned */
   301         -#pragma warn -spa /* Suspicious pointer arithmetic */
   302         -#endif
   303         -
   304         -/* Needed for various definitions... */
   305         -#ifndef _GNU_SOURCE
   306         -# define _GNU_SOURCE
   307         -#endif
   308         -
   309         -#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
   310         -# define _BSD_SOURCE
   311         -#endif
   312         -
   313         -/*
   314         -** Include standard header files as necessary
   315         -*/
   316         -#ifdef HAVE_STDINT_H
   317         -#include <stdint.h>
   318         -#endif
   319         -#ifdef HAVE_INTTYPES_H
   320         -#include <inttypes.h>
   321         -#endif
   322         -
   323         -/*
   324         -** The following macros are used to cast pointers to integers and
   325         -** integers to pointers.  The way you do this varies from one compiler
   326         -** to the next, so we have developed the following set of #if statements
   327         -** to generate appropriate macros for a wide range of compilers.
   328         -**
   329         -** The correct "ANSI" way to do this is to use the intptr_t type. 
   330         -** Unfortunately, that typedef is not available on all compilers, or
   331         -** if it is available, it requires an #include of specific headers
   332         -** that vary from one machine to the next.
   333         -**
   334         -** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
   335         -** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
   336         -** So we have to define the macros in different ways depending on the
   337         -** compiler.
   338         -*/
   339         -#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
   340         -# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
   341         -# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
   342         -#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
   343         -# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
   344         -# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
   345         -#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
   346         -# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
   347         -# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
   348         -#else                          /* Generates a warning - but it always works */
   349         -# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
   350         -# define SQLITE_PTR_TO_INT(X)  ((int)(X))
   351         -#endif
   352         -
   353         -/*
   354         -** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
   355         -** 0 means mutexes are permanently disable and the library is never
   356         -** threadsafe.  1 means the library is serialized which is the highest
   357         -** level of threadsafety.  2 means the library is multithreaded - multiple
   358         -** threads can use SQLite as long as no two threads try to use the same
   359         -** database connection at the same time.
   360         -**
   361         -** Older versions of SQLite used an optional THREADSAFE macro.
   362         -** We support that for legacy.
   363         -*/
   364         -#if !defined(SQLITE_THREADSAFE)
   365         -# if defined(THREADSAFE)
   366         -#   define SQLITE_THREADSAFE THREADSAFE
   367         -# else
   368         -#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
   369         -# endif
   370         -#endif
   371         -
   372         -/*
   373         -** Powersafe overwrite is on by default.  But can be turned off using
   374         -** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
   375         -*/
   376         -#ifndef SQLITE_POWERSAFE_OVERWRITE
   377         -# define SQLITE_POWERSAFE_OVERWRITE 1
   378         -#endif
   379         -
   380         -/*
   381         -** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
   382         -** It determines whether or not the features related to 
   383         -** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
   384         -** be overridden at runtime using the sqlite3_config() API.
   385         -*/
   386         -#if !defined(SQLITE_DEFAULT_MEMSTATUS)
   387         -# define SQLITE_DEFAULT_MEMSTATUS 1
   388         -#endif
   389         -
   390         -/*
   391         -** Exactly one of the following macros must be defined in order to
   392         -** specify which memory allocation subsystem to use.
   393         -**
   394         -**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
   395         -**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
   396         -**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
   397         -**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
   398         -**
   399         -** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
   400         -** assert() macro is enabled, each call into the Win32 native heap subsystem
   401         -** will cause HeapValidate to be called.  If heap validation should fail, an
   402         -** assertion will be triggered.
   403         -**
   404         -** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
   405         -** the default.
   406         -*/
   407         -#if defined(SQLITE_SYSTEM_MALLOC) \
   408         -  + defined(SQLITE_WIN32_MALLOC) \
   409         -  + defined(SQLITE_ZERO_MALLOC) \
   410         -  + defined(SQLITE_MEMDEBUG)>1
   411         -# error "Two or more of the following compile-time configuration options\
   412         - are defined but at most one is allowed:\
   413         - SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
   414         - SQLITE_ZERO_MALLOC"
   415         -#endif
   416         -#if defined(SQLITE_SYSTEM_MALLOC) \
   417         -  + defined(SQLITE_WIN32_MALLOC) \
   418         -  + defined(SQLITE_ZERO_MALLOC) \
   419         -  + defined(SQLITE_MEMDEBUG)==0
   420         -# define SQLITE_SYSTEM_MALLOC 1
   421         -#endif
   422         -
   423         -/*
   424         -** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
   425         -** sizes of memory allocations below this value where possible.
   426         -*/
   427         -#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
   428         -# define SQLITE_MALLOC_SOFT_LIMIT 1024
   429         -#endif
   430         -
   431         -/*
   432         -** We need to define _XOPEN_SOURCE as follows in order to enable
   433         -** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
   434         -** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
   435         -** it.
   436         -*/
   437         -#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
   438         -#  define _XOPEN_SOURCE 600
   439         -#endif
   440         -
   441         -/*
   442         -** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
   443         -** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
   444         -** make it true by defining or undefining NDEBUG.
   445         -**
   446         -** Setting NDEBUG makes the code smaller and faster by disabling the
   447         -** assert() statements in the code.  So we want the default action
   448         -** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
   449         -** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
   450         -** feature.
   451         -*/
   452         -#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
   453         -# define NDEBUG 1
   454         -#endif
   455         -#if defined(NDEBUG) && defined(SQLITE_DEBUG)
   456         -# undef NDEBUG
   457         -#endif
   458         -
   459         -/*
   460         -** The testcase() macro is used to aid in coverage testing.  When 
   461         -** doing coverage testing, the condition inside the argument to
   462         -** testcase() must be evaluated both true and false in order to
   463         -** get full branch coverage.  The testcase() macro is inserted
   464         -** to help ensure adequate test coverage in places where simple
   465         -** condition/decision coverage is inadequate.  For example, testcase()
   466         -** can be used to make sure boundary values are tested.  For
   467         -** bitmask tests, testcase() can be used to make sure each bit
   468         -** is significant and used at least once.  On switch statements
   469         -** where multiple cases go to the same block of code, testcase()
   470         -** can insure that all cases are evaluated.
   471         -**
   472         -*/
   473         -#ifdef SQLITE_COVERAGE_TEST
   474         -SQLITE_PRIVATE   void sqlite3Coverage(int);
   475         -# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
   476         -#else
   477         -# define testcase(X)
   478         -#endif
   479         -
   480         -/*
   481         -** The TESTONLY macro is used to enclose variable declarations or
   482         -** other bits of code that are needed to support the arguments
   483         -** within testcase() and assert() macros.
   484         -*/
   485         -#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
   486         -# define TESTONLY(X)  X
   487         -#else
   488         -# define TESTONLY(X)
   489         -#endif
   490         -
   491         -/*
   492         -** Sometimes we need a small amount of code such as a variable initialization
   493         -** to setup for a later assert() statement.  We do not want this code to
   494         -** appear when assert() is disabled.  The following macro is therefore
   495         -** used to contain that setup code.  The "VVA" acronym stands for
   496         -** "Verification, Validation, and Accreditation".  In other words, the
   497         -** code within VVA_ONLY() will only run during verification processes.
   498         -*/
   499         -#ifndef NDEBUG
   500         -# define VVA_ONLY(X)  X
   501         -#else
   502         -# define VVA_ONLY(X)
   503         -#endif
   504         -
   505         -/*
   506         -** The ALWAYS and NEVER macros surround boolean expressions which 
   507         -** are intended to always be true or false, respectively.  Such
   508         -** expressions could be omitted from the code completely.  But they
   509         -** are included in a few cases in order to enhance the resilience
   510         -** of SQLite to unexpected behavior - to make the code "self-healing"
   511         -** or "ductile" rather than being "brittle" and crashing at the first
   512         -** hint of unplanned behavior.
   513         -**
   514         -** In other words, ALWAYS and NEVER are added for defensive code.
   515         -**
   516         -** When doing coverage testing ALWAYS and NEVER are hard-coded to
   517         -** be true and false so that the unreachable code they specify will
   518         -** not be counted as untested code.
   519         -*/
   520         -#if defined(SQLITE_COVERAGE_TEST)
   521         -# define ALWAYS(X)      (1)
   522         -# define NEVER(X)       (0)
   523         -#elif !defined(NDEBUG)
   524         -# define ALWAYS(X)      ((X)?1:(assert(0),0))
   525         -# define NEVER(X)       ((X)?(assert(0),1):0)
   526         -#else
   527         -# define ALWAYS(X)      (X)
   528         -# define NEVER(X)       (X)
   529         -#endif
   530         -
   531         -/*
   532         -** Return true (non-zero) if the input is a integer that is too large
   533         -** to fit in 32-bits.  This macro is used inside of various testcase()
   534         -** macros to verify that we have tested SQLite for large-file support.
   535         -*/
   536         -#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
   537         -
   538         -/*
   539         -** The macro unlikely() is a hint that surrounds a boolean
   540         -** expression that is usually false.  Macro likely() surrounds
   541         -** a boolean expression that is usually true.  These hints could,
   542         -** in theory, be used by the compiler to generate better code, but
   543         -** currently they are just comments for human readers.
   544         -*/
   545         -#define likely(X)    (X)
   546         -#define unlikely(X)  (X)
   547         -
   548         -/************** Include sqlite3.h in the middle of sqliteInt.h ***************/
   549     28   /************** Begin file sqlite3.h *****************************************/
   550     29   /*
   551     30   ** 2001 September 15
   552     31   **
   553     32   ** The author disclaims copyright to this source code.  In place of
   554     33   ** a legal notice, here is a blessing:
   555     34   **
................................................................................
   654    133   **
   655    134   ** See also: [sqlite3_libversion()],
   656    135   ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
   657    136   ** [sqlite_version()] and [sqlite_source_id()].
   658    137   */
   659    138   #define SQLITE_VERSION        "3.8.1"
   660    139   #define SQLITE_VERSION_NUMBER 3008001
   661         -#define SQLITE_SOURCE_ID      "2013-09-12 02:09:05 75a8a8c1b39725d36db627536d0c69401f8e0815"
          140  +#define SQLITE_SOURCE_ID      "2013-10-12 20:22:00 f0cf8c85dcbcc7778aed2816792c368d777f79cb"
   662    141   
   663    142   /*
   664    143   ** CAPI3REF: Run-Time Library Version Numbers
   665    144   ** KEYWORDS: sqlite3_version, sqlite3_sourceid
   666    145   **
   667    146   ** These interfaces provide the same information as the [SQLITE_VERSION],
   668    147   ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
................................................................................
  2162   1641   ** log message after formatting via [sqlite3_snprintf()].
  2163   1642   ** The SQLite logging interface is not reentrant; the logger function
  2164   1643   ** supplied by the application must not invoke any SQLite interface.
  2165   1644   ** In a multi-threaded application, the application-defined logger
  2166   1645   ** function must be threadsafe. </dd>
  2167   1646   **
  2168   1647   ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2169         -** <dd> This option takes a single argument of type int. If non-zero, then
         1648  +** <dd>^(This option takes a single argument of type int. If non-zero, then
  2170   1649   ** URI handling is globally enabled. If the parameter is zero, then URI handling
  2171         -** is globally disabled. If URI handling is globally enabled, all filenames
         1650  +** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  2172   1651   ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  2173   1652   ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2174   1653   ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2175         -** connection is opened. If it is globally disabled, filenames are
         1654  +** connection is opened. ^If it is globally disabled, filenames are
  2176   1655   ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2177         -** database connection is opened. By default, URI handling is globally
         1656  +** database connection is opened. ^(By default, URI handling is globally
  2178   1657   ** disabled. The default value may be changed by compiling with the
  2179         -** [SQLITE_USE_URI] symbol defined.
         1658  +** [SQLITE_USE_URI] symbol defined.)^
  2180   1659   **
  2181   1660   ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2182         -** <dd> This option takes a single integer argument which is interpreted as
         1661  +** <dd>^This option takes a single integer argument which is interpreted as
  2183   1662   ** a boolean in order to enable or disable the use of covering indices for
  2184         -** full table scans in the query optimizer.  The default setting is determined
         1663  +** full table scans in the query optimizer.  ^The default setting is determined
  2185   1664   ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2186   1665   ** if that compile-time option is omitted.
  2187   1666   ** The ability to disable the use of covering indices for full table scans
  2188   1667   ** is because some incorrectly coded legacy applications might malfunction
  2189         -** malfunction when the optimization is enabled.  Providing the ability to
         1668  +** when the optimization is enabled.  Providing the ability to
  2190   1669   ** disable the optimization allows the older, buggy application code to work
  2191   1670   ** without change even with newer versions of SQLite.
  2192   1671   **
  2193   1672   ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2194   1673   ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2195   1674   ** <dd> These options are obsolete and should not be used by new code.
  2196   1675   ** They are retained for backwards compatibility but are now no-ops.
................................................................................
  2211   1690   ** the connection being passed as the second parameter is being closed. The
  2212   1691   ** third parameter is passed NULL In this case.  An example of using this
  2213   1692   ** configuration option can be seen in the "test_sqllog.c" source file in
  2214   1693   ** the canonical SQLite source tree.</dd>
  2215   1694   **
  2216   1695   ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2217   1696   ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2218         -** <dd>SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
         1697  +** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2219   1698   ** that are the default mmap size limit (the default setting for
  2220   1699   ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2221         -** The default setting can be overridden by each database connection using
         1700  +** ^The default setting can be overridden by each database connection using
  2222   1701   ** either the [PRAGMA mmap_size] command, or by using the
  2223         -** [SQLITE_FCNTL_MMAP_SIZE] file control.  The maximum allowed mmap size
         1702  +** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
  2224   1703   ** cannot be changed at run-time.  Nor may the maximum allowed mmap size
  2225   1704   ** exceed the compile-time maximum mmap size set by the
  2226         -** [SQLITE_MAX_MMAP_SIZE] compile-time option.  
  2227         -** If either argument to this option is negative, then that argument is
         1705  +** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
         1706  +** ^If either argument to this option is negative, then that argument is
  2228   1707   ** changed to its compile-time default.
  2229   1708   ** </dl>
  2230   1709   */
  2231   1710   #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
  2232   1711   #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
  2233   1712   #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
  2234   1713   #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
................................................................................
  7844   7323   }  /* end of the 'extern "C"' block */
  7845   7324   #endif
  7846   7325   
  7847   7326   #endif  /* ifndef _SQLITE3RTREE_H_ */
  7848   7327   
  7849   7328   
  7850   7329   /************** End of sqlite3.h *********************************************/
         7330  +/************** Begin file sqliteInt.h ***************************************/
         7331  +/*
         7332  +** 2001 September 15
         7333  +**
         7334  +** The author disclaims copyright to this source code.  In place of
         7335  +** a legal notice, here is a blessing:
         7336  +**
         7337  +**    May you do good and not evil.
         7338  +**    May you find forgiveness for yourself and forgive others.
         7339  +**    May you share freely, never taking more than you give.
         7340  +**
         7341  +*************************************************************************
         7342  +** Internal interface definitions for SQLite.
         7343  +**
         7344  +*/
         7345  +#ifndef _SQLITEINT_H_
         7346  +#define _SQLITEINT_H_
         7347  +
         7348  +/*
         7349  +** These #defines should enable >2GB file support on POSIX if the
         7350  +** underlying operating system supports it.  If the OS lacks
         7351  +** large file support, or if the OS is windows, these should be no-ops.
         7352  +**
         7353  +** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
         7354  +** system #includes.  Hence, this block of code must be the very first
         7355  +** code in all source files.
         7356  +**
         7357  +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
         7358  +** on the compiler command line.  This is necessary if you are compiling
         7359  +** on a recent machine (ex: Red Hat 7.2) but you want your code to work
         7360  +** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
         7361  +** without this option, LFS is enable.  But LFS does not exist in the kernel
         7362  +** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
         7363  +** portability you should omit LFS.
         7364  +**
         7365  +** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
         7366  +*/
         7367  +#ifndef SQLITE_DISABLE_LFS
         7368  +# define _LARGE_FILE       1
         7369  +# ifndef _FILE_OFFSET_BITS
         7370  +#   define _FILE_OFFSET_BITS 64
         7371  +# endif
         7372  +# define _LARGEFILE_SOURCE 1
         7373  +#endif
         7374  +
         7375  +/*
         7376  +** Include the configuration header output by 'configure' if we're using the
         7377  +** autoconf-based build
         7378  +*/
         7379  +#ifdef _HAVE_SQLITE_CONFIG_H
         7380  +#include "config.h"
         7381  +#endif
         7382  +
         7383  +/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
         7384  +/************** Begin file sqliteLimit.h *************************************/
         7385  +/*
         7386  +** 2007 May 7
         7387  +**
         7388  +** The author disclaims copyright to this source code.  In place of
         7389  +** a legal notice, here is a blessing:
         7390  +**
         7391  +**    May you do good and not evil.
         7392  +**    May you find forgiveness for yourself and forgive others.
         7393  +**    May you share freely, never taking more than you give.
         7394  +**
         7395  +*************************************************************************
         7396  +** 
         7397  +** This file defines various limits of what SQLite can process.
         7398  +*/
         7399  +
         7400  +/*
         7401  +** The maximum length of a TEXT or BLOB in bytes.   This also
         7402  +** limits the size of a row in a table or index.
         7403  +**
         7404  +** The hard limit is the ability of a 32-bit signed integer
         7405  +** to count the size: 2^31-1 or 2147483647.
         7406  +*/
         7407  +#ifndef SQLITE_MAX_LENGTH
         7408  +# define SQLITE_MAX_LENGTH 1000000000
         7409  +#endif
         7410  +
         7411  +/*
         7412  +** This is the maximum number of
         7413  +**
         7414  +**    * Columns in a table
         7415  +**    * Columns in an index
         7416  +**    * Columns in a view
         7417  +**    * Terms in the SET clause of an UPDATE statement
         7418  +**    * Terms in the result set of a SELECT statement
         7419  +**    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
         7420  +**    * Terms in the VALUES clause of an INSERT statement
         7421  +**
         7422  +** The hard upper limit here is 32676.  Most database people will
         7423  +** tell you that in a well-normalized database, you usually should
         7424  +** not have more than a dozen or so columns in any table.  And if
         7425  +** that is the case, there is no point in having more than a few
         7426  +** dozen values in any of the other situations described above.
         7427  +*/
         7428  +#ifndef SQLITE_MAX_COLUMN
         7429  +# define SQLITE_MAX_COLUMN 2000
         7430  +#endif
         7431  +
         7432  +/*
         7433  +** The maximum length of a single SQL statement in bytes.
         7434  +**
         7435  +** It used to be the case that setting this value to zero would
         7436  +** turn the limit off.  That is no longer true.  It is not possible
         7437  +** to turn this limit off.
         7438  +*/
         7439  +#ifndef SQLITE_MAX_SQL_LENGTH
         7440  +# define SQLITE_MAX_SQL_LENGTH 1000000000
         7441  +#endif
         7442  +
         7443  +/*
         7444  +** The maximum depth of an expression tree. This is limited to 
         7445  +** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
         7446  +** want to place more severe limits on the complexity of an 
         7447  +** expression.
         7448  +**
         7449  +** A value of 0 used to mean that the limit was not enforced.
         7450  +** But that is no longer true.  The limit is now strictly enforced
         7451  +** at all times.
         7452  +*/
         7453  +#ifndef SQLITE_MAX_EXPR_DEPTH
         7454  +# define SQLITE_MAX_EXPR_DEPTH 1000
         7455  +#endif
         7456  +
         7457  +/*
         7458  +** The maximum number of terms in a compound SELECT statement.
         7459  +** The code generator for compound SELECT statements does one
         7460  +** level of recursion for each term.  A stack overflow can result
         7461  +** if the number of terms is too large.  In practice, most SQL
         7462  +** never has more than 3 or 4 terms.  Use a value of 0 to disable
         7463  +** any limit on the number of terms in a compount SELECT.
         7464  +*/
         7465  +#ifndef SQLITE_MAX_COMPOUND_SELECT
         7466  +# define SQLITE_MAX_COMPOUND_SELECT 500
         7467  +#endif
         7468  +
         7469  +/*
         7470  +** The maximum number of opcodes in a VDBE program.
         7471  +** Not currently enforced.
         7472  +*/
         7473  +#ifndef SQLITE_MAX_VDBE_OP
         7474  +# define SQLITE_MAX_VDBE_OP 25000
         7475  +#endif
         7476  +
         7477  +/*
         7478  +** The maximum number of arguments to an SQL function.
         7479  +*/
         7480  +#ifndef SQLITE_MAX_FUNCTION_ARG
         7481  +# define SQLITE_MAX_FUNCTION_ARG 127
         7482  +#endif
         7483  +
         7484  +/*
         7485  +** The maximum number of in-memory pages to use for the main database
         7486  +** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
         7487  +*/
         7488  +#ifndef SQLITE_DEFAULT_CACHE_SIZE
         7489  +# define SQLITE_DEFAULT_CACHE_SIZE  2000
         7490  +#endif
         7491  +#ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
         7492  +# define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
         7493  +#endif
         7494  +
         7495  +/*
         7496  +** The default number of frames to accumulate in the log file before
         7497  +** checkpointing the database in WAL mode.
         7498  +*/
         7499  +#ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
         7500  +# define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
         7501  +#endif
         7502  +
         7503  +/*
         7504  +** The maximum number of attached databases.  This must be between 0
         7505  +** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
         7506  +** is used internally to track attached databases.
         7507  +*/
         7508  +#ifndef SQLITE_MAX_ATTACHED
         7509  +# define SQLITE_MAX_ATTACHED 10
         7510  +#endif
         7511  +
         7512  +
         7513  +/*
         7514  +** The maximum value of a ?nnn wildcard that the parser will accept.
         7515  +*/
         7516  +#ifndef SQLITE_MAX_VARIABLE_NUMBER
         7517  +# define SQLITE_MAX_VARIABLE_NUMBER 999
         7518  +#endif
         7519  +
         7520  +/* Maximum page size.  The upper bound on this value is 65536.  This a limit
         7521  +** imposed by the use of 16-bit offsets within each page.
         7522  +**
         7523  +** Earlier versions of SQLite allowed the user to change this value at
         7524  +** compile time. This is no longer permitted, on the grounds that it creates
         7525  +** a library that is technically incompatible with an SQLite library 
         7526  +** compiled with a different limit. If a process operating on a database 
         7527  +** with a page-size of 65536 bytes crashes, then an instance of SQLite 
         7528  +** compiled with the default page-size limit will not be able to rollback 
         7529  +** the aborted transaction. This could lead to database corruption.
         7530  +*/
         7531  +#ifdef SQLITE_MAX_PAGE_SIZE
         7532  +# undef SQLITE_MAX_PAGE_SIZE
         7533  +#endif
         7534  +#define SQLITE_MAX_PAGE_SIZE 65536
         7535  +
         7536  +
         7537  +/*
         7538  +** The default size of a database page.
         7539  +*/
         7540  +#ifndef SQLITE_DEFAULT_PAGE_SIZE
         7541  +# define SQLITE_DEFAULT_PAGE_SIZE 1024
         7542  +#endif
         7543  +#if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
         7544  +# undef SQLITE_DEFAULT_PAGE_SIZE
         7545  +# define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
         7546  +#endif
         7547  +
         7548  +/*
         7549  +** Ordinarily, if no value is explicitly provided, SQLite creates databases
         7550  +** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
         7551  +** device characteristics (sector-size and atomic write() support),
         7552  +** SQLite may choose a larger value. This constant is the maximum value
         7553  +** SQLite will choose on its own.
         7554  +*/
         7555  +#ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
         7556  +# define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
         7557  +#endif
         7558  +#if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
         7559  +# undef SQLITE_MAX_DEFAULT_PAGE_SIZE
         7560  +# define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
         7561  +#endif
         7562  +
         7563  +
         7564  +/*
         7565  +** Maximum number of pages in one database file.
         7566  +**
         7567  +** This is really just the default value for the max_page_count pragma.
         7568  +** This value can be lowered (or raised) at run-time using that the
         7569  +** max_page_count macro.
         7570  +*/
         7571  +#ifndef SQLITE_MAX_PAGE_COUNT
         7572  +# define SQLITE_MAX_PAGE_COUNT 1073741823
         7573  +#endif
         7574  +
         7575  +/*
         7576  +** Maximum length (in bytes) of the pattern in a LIKE or GLOB
         7577  +** operator.
         7578  +*/
         7579  +#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
         7580  +# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
         7581  +#endif
         7582  +
         7583  +/*
         7584  +** Maximum depth of recursion for triggers.
         7585  +**
         7586  +** A value of 1 means that a trigger program will not be able to itself
         7587  +** fire any triggers. A value of 0 means that no trigger programs at all 
         7588  +** may be executed.
         7589  +*/
         7590  +#ifndef SQLITE_MAX_TRIGGER_DEPTH
         7591  +# define SQLITE_MAX_TRIGGER_DEPTH 1000
         7592  +#endif
         7593  +
         7594  +/************** End of sqliteLimit.h *****************************************/
  7851   7595   /************** Continuing where we left off in sqliteInt.h ******************/
         7596  +
         7597  +/* Disable nuisance warnings on Borland compilers */
         7598  +#if defined(__BORLANDC__)
         7599  +#pragma warn -rch /* unreachable code */
         7600  +#pragma warn -ccc /* Condition is always true or false */
         7601  +#pragma warn -aus /* Assigned value is never used */
         7602  +#pragma warn -csu /* Comparing signed and unsigned */
         7603  +#pragma warn -spa /* Suspicious pointer arithmetic */
         7604  +#endif
         7605  +
         7606  +/* Needed for various definitions... */
         7607  +#ifndef _GNU_SOURCE
         7608  +# define _GNU_SOURCE
         7609  +#endif
         7610  +
         7611  +#if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
         7612  +# define _BSD_SOURCE
         7613  +#endif
         7614  +
         7615  +/*
         7616  +** Include standard header files as necessary
         7617  +*/
         7618  +#ifdef HAVE_STDINT_H
         7619  +#include <stdint.h>
         7620  +#endif
         7621  +#ifdef HAVE_INTTYPES_H
         7622  +#include <inttypes.h>
         7623  +#endif
         7624  +
         7625  +/*
         7626  +** The following macros are used to cast pointers to integers and
         7627  +** integers to pointers.  The way you do this varies from one compiler
         7628  +** to the next, so we have developed the following set of #if statements
         7629  +** to generate appropriate macros for a wide range of compilers.
         7630  +**
         7631  +** The correct "ANSI" way to do this is to use the intptr_t type. 
         7632  +** Unfortunately, that typedef is not available on all compilers, or
         7633  +** if it is available, it requires an #include of specific headers
         7634  +** that vary from one machine to the next.
         7635  +**
         7636  +** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
         7637  +** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
         7638  +** So we have to define the macros in different ways depending on the
         7639  +** compiler.
         7640  +*/
         7641  +#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
         7642  +# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
         7643  +# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
         7644  +#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
         7645  +# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
         7646  +# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
         7647  +#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
         7648  +# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
         7649  +# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
         7650  +#else                          /* Generates a warning - but it always works */
         7651  +# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
         7652  +# define SQLITE_PTR_TO_INT(X)  ((int)(X))
         7653  +#endif
         7654  +
         7655  +/*
         7656  +** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
         7657  +** 0 means mutexes are permanently disable and the library is never
         7658  +** threadsafe.  1 means the library is serialized which is the highest
         7659  +** level of threadsafety.  2 means the library is multithreaded - multiple
         7660  +** threads can use SQLite as long as no two threads try to use the same
         7661  +** database connection at the same time.
         7662  +**
         7663  +** Older versions of SQLite used an optional THREADSAFE macro.
         7664  +** We support that for legacy.
         7665  +*/
         7666  +#if !defined(SQLITE_THREADSAFE)
         7667  +# if defined(THREADSAFE)
         7668  +#   define SQLITE_THREADSAFE THREADSAFE
         7669  +# else
         7670  +#   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
         7671  +# endif
         7672  +#endif
         7673  +
         7674  +/*
         7675  +** Powersafe overwrite is on by default.  But can be turned off using
         7676  +** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
         7677  +*/
         7678  +#ifndef SQLITE_POWERSAFE_OVERWRITE
         7679  +# define SQLITE_POWERSAFE_OVERWRITE 1
         7680  +#endif
         7681  +
         7682  +/*
         7683  +** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
         7684  +** It determines whether or not the features related to 
         7685  +** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
         7686  +** be overridden at runtime using the sqlite3_config() API.
         7687  +*/
         7688  +#if !defined(SQLITE_DEFAULT_MEMSTATUS)
         7689  +# define SQLITE_DEFAULT_MEMSTATUS 1
         7690  +#endif
         7691  +
         7692  +/*
         7693  +** Exactly one of the following macros must be defined in order to
         7694  +** specify which memory allocation subsystem to use.
         7695  +**
         7696  +**     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
         7697  +**     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
         7698  +**     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
         7699  +**     SQLITE_MEMDEBUG               // Debugging version of system malloc()
         7700  +**
         7701  +** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
         7702  +** assert() macro is enabled, each call into the Win32 native heap subsystem
         7703  +** will cause HeapValidate to be called.  If heap validation should fail, an
         7704  +** assertion will be triggered.
         7705  +**
         7706  +** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
         7707  +** the default.
         7708  +*/
         7709  +#if defined(SQLITE_SYSTEM_MALLOC) \
         7710  +  + defined(SQLITE_WIN32_MALLOC) \
         7711  +  + defined(SQLITE_ZERO_MALLOC) \
         7712  +  + defined(SQLITE_MEMDEBUG)>1
         7713  +# error "Two or more of the following compile-time configuration options\
         7714  + are defined but at most one is allowed:\
         7715  + SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
         7716  + SQLITE_ZERO_MALLOC"
         7717  +#endif
         7718  +#if defined(SQLITE_SYSTEM_MALLOC) \
         7719  +  + defined(SQLITE_WIN32_MALLOC) \
         7720  +  + defined(SQLITE_ZERO_MALLOC) \
         7721  +  + defined(SQLITE_MEMDEBUG)==0
         7722  +# define SQLITE_SYSTEM_MALLOC 1
         7723  +#endif
         7724  +
         7725  +/*
         7726  +** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
         7727  +** sizes of memory allocations below this value where possible.
         7728  +*/
         7729  +#if !defined(SQLITE_MALLOC_SOFT_LIMIT)
         7730  +# define SQLITE_MALLOC_SOFT_LIMIT 1024
         7731  +#endif
         7732  +
         7733  +/*
         7734  +** We need to define _XOPEN_SOURCE as follows in order to enable
         7735  +** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
         7736  +** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
         7737  +** it.
         7738  +*/
         7739  +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
         7740  +#  define _XOPEN_SOURCE 600
         7741  +#endif
         7742  +
         7743  +/*
         7744  +** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
         7745  +** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
         7746  +** make it true by defining or undefining NDEBUG.
         7747  +**
         7748  +** Setting NDEBUG makes the code smaller and faster by disabling the
         7749  +** assert() statements in the code.  So we want the default action
         7750  +** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
         7751  +** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
         7752  +** feature.
         7753  +*/
         7754  +#if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
         7755  +# define NDEBUG 1
         7756  +#endif
         7757  +#if defined(NDEBUG) && defined(SQLITE_DEBUG)
         7758  +# undef NDEBUG
         7759  +#endif
         7760  +
         7761  +/*
         7762  +** The testcase() macro is used to aid in coverage testing.  When 
         7763  +** doing coverage testing, the condition inside the argument to
         7764  +** testcase() must be evaluated both true and false in order to
         7765  +** get full branch coverage.  The testcase() macro is inserted
         7766  +** to help ensure adequate test coverage in places where simple
         7767  +** condition/decision coverage is inadequate.  For example, testcase()
         7768  +** can be used to make sure boundary values are tested.  For
         7769  +** bitmask tests, testcase() can be used to make sure each bit
         7770  +** is significant and used at least once.  On switch statements
         7771  +** where multiple cases go to the same block of code, testcase()
         7772  +** can insure that all cases are evaluated.
         7773  +**
         7774  +*/
         7775  +#ifdef SQLITE_COVERAGE_TEST
         7776  +SQLITE_PRIVATE   void sqlite3Coverage(int);
         7777  +# define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
         7778  +#else
         7779  +# define testcase(X)
         7780  +#endif
         7781  +
         7782  +/*
         7783  +** The TESTONLY macro is used to enclose variable declarations or
         7784  +** other bits of code that are needed to support the arguments
         7785  +** within testcase() and assert() macros.
         7786  +*/
         7787  +#if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
         7788  +# define TESTONLY(X)  X
         7789  +#else
         7790  +# define TESTONLY(X)
         7791  +#endif
         7792  +
         7793  +/*
         7794  +** Sometimes we need a small amount of code such as a variable initialization
         7795  +** to setup for a later assert() statement.  We do not want this code to
         7796  +** appear when assert() is disabled.  The following macro is therefore
         7797  +** used to contain that setup code.  The "VVA" acronym stands for
         7798  +** "Verification, Validation, and Accreditation".  In other words, the
         7799  +** code within VVA_ONLY() will only run during verification processes.
         7800  +*/
         7801  +#ifndef NDEBUG
         7802  +# define VVA_ONLY(X)  X
         7803  +#else
         7804  +# define VVA_ONLY(X)
         7805  +#endif
         7806  +
         7807  +/*
         7808  +** The ALWAYS and NEVER macros surround boolean expressions which 
         7809  +** are intended to always be true or false, respectively.  Such
         7810  +** expressions could be omitted from the code completely.  But they
         7811  +** are included in a few cases in order to enhance the resilience
         7812  +** of SQLite to unexpected behavior - to make the code "self-healing"
         7813  +** or "ductile" rather than being "brittle" and crashing at the first
         7814  +** hint of unplanned behavior.
         7815  +**
         7816  +** In other words, ALWAYS and NEVER are added for defensive code.
         7817  +**
         7818  +** When doing coverage testing ALWAYS and NEVER are hard-coded to
         7819  +** be true and false so that the unreachable code they specify will
         7820  +** not be counted as untested code.
         7821  +*/
         7822  +#if defined(SQLITE_COVERAGE_TEST)
         7823  +# define ALWAYS(X)      (1)
         7824  +# define NEVER(X)       (0)
         7825  +#elif !defined(NDEBUG)
         7826  +# define ALWAYS(X)      ((X)?1:(assert(0),0))
         7827  +# define NEVER(X)       ((X)?(assert(0),1):0)
         7828  +#else
         7829  +# define ALWAYS(X)      (X)
         7830  +# define NEVER(X)       (X)
         7831  +#endif
         7832  +
         7833  +/*
         7834  +** Return true (non-zero) if the input is a integer that is too large
         7835  +** to fit in 32-bits.  This macro is used inside of various testcase()
         7836  +** macros to verify that we have tested SQLite for large-file support.
         7837  +*/
         7838  +#define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
         7839  +
         7840  +/*
         7841  +** The macro unlikely() is a hint that surrounds a boolean
         7842  +** expression that is usually false.  Macro likely() surrounds
         7843  +** a boolean expression that is usually true.  These hints could,
         7844  +** in theory, be used by the compiler to generate better code, but
         7845  +** currently they are just comments for human readers.
         7846  +*/
         7847  +#define likely(X)    (X)
         7848  +#define unlikely(X)  (X)
         7849  +
  7852   7850   /************** Include hash.h in the middle of sqliteInt.h ******************/
  7853   7851   /************** Begin file hash.h ********************************************/
  7854   7852   /*
  7855   7853   ** 2001 September 22
  7856   7854   **
  7857   7855   ** The author disclaims copyright to this source code.  In place of
  7858   7856   ** a legal notice, here is a blessing:
................................................................................
  8270   8268   */
  8271   8269   #ifdef SQLITE_64BIT_STATS
  8272   8270    typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
  8273   8271   #else
  8274   8272    typedef u32 tRowcnt;    /* 32-bit is the default */
  8275   8273   #endif
  8276   8274   
         8275  +/*
         8276  +** Estimated quantities used for query planning are stored as 16-bit
         8277  +** logarithms.  For quantity X, the value stored is 10*log2(X).  This
         8278  +** gives a possible range of values of approximately 1.0e986 to 1e-986.
         8279  +** But the allowed values are "grainy".  Not every value is representable.
         8280  +** For example, quantities 16 and 17 are both represented by a LogEst
         8281  +** of 40.  However, since LogEst quantatites are suppose to be estimates,
         8282  +** not exact values, this imprecision is not a problem.
         8283  +**
         8284  +** "LogEst" is short for "Logarithimic Estimate".
         8285  +**
         8286  +** Examples:
         8287  +**      1 -> 0              20 -> 43          10000 -> 132
         8288  +**      2 -> 10             25 -> 46          25000 -> 146
         8289  +**      3 -> 16            100 -> 66        1000000 -> 199
         8290  +**      4 -> 20           1000 -> 99        1048576 -> 200
         8291  +**     10 -> 33           1024 -> 100    4294967296 -> 320
         8292  +**
         8293  +** The LogEst can be negative to indicate fractional values. 
         8294  +** Examples:
         8295  +**
         8296  +**    0.5 -> -10           0.1 -> -33        0.0625 -> -40
         8297  +*/
         8298  +typedef INT16_TYPE LogEst;
         8299  +
  8277   8300   /*
  8278   8301   ** Macros to determine whether the machine is big or little endian,
  8279   8302   ** evaluated at runtime.
  8280   8303   */
  8281   8304   #ifdef SQLITE_AMALGAMATION
  8282   8305   SQLITE_PRIVATE const int sqlite3one = 1;
  8283   8306   #else
................................................................................
 10250  10273   #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
 10251  10274   #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
 10252  10275   #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
 10253  10276   #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
 10254  10277   #define SQLITE_Transitive     0x0200   /* Transitive constraints */
 10255  10278   #define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
 10256  10279   #define SQLITE_Stat3          0x0800   /* Use the SQLITE_STAT3 table */
        10280  +#define SQLITE_AdjustOutEst   0x1000   /* Adjust output estimates using WHERE */
 10257  10281   #define SQLITE_AllOpts        0xffff   /* All optimizations */
 10258  10282   
 10259  10283   /*
 10260  10284   ** Macros for testing whether or not optimizations are enabled or disabled.
 10261  10285   */
 10262  10286   #ifndef SQLITE_OMIT_BUILTIN_TEST
 10263  10287   #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
................................................................................
 10416  10440     char *zName;     /* Name of this column */
 10417  10441     Expr *pDflt;     /* Default value of this column */
 10418  10442     char *zDflt;     /* Original text of the default value */
 10419  10443     char *zType;     /* Data type for this column */
 10420  10444     char *zColl;     /* Collating sequence.  If NULL, use the default */
 10421  10445     u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
 10422  10446     char affinity;   /* One of the SQLITE_AFF_... values */
 10423         -  u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
        10447  +  u8 szEst;        /* Estimated size of this column.  INT==1 */
        10448  +  u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
 10424  10449   };
 10425  10450   
 10426  10451   /* Allowed values for Column.colFlags:
 10427  10452   */
 10428  10453   #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
 10429  10454   #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
 10430  10455   
................................................................................
 10580  10605     ExprList *pCheck;    /* All CHECK constraints */
 10581  10606   #endif
 10582  10607     tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
 10583  10608     int tnum;            /* Root BTree node for this table (see note above) */
 10584  10609     i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
 10585  10610     i16 nCol;            /* Number of columns in this table */
 10586  10611     u16 nRef;            /* Number of pointers to this Table */
        10612  +  LogEst szTabRow;     /* Estimated size of each table row in bytes */
 10587  10613     u8 tabFlags;         /* Mask of TF_* values */
 10588  10614     u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
 10589  10615   #ifndef SQLITE_OMIT_ALTERTABLE
 10590  10616     int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
 10591  10617   #endif
 10592  10618   #ifndef SQLITE_OMIT_VIRTUALTABLE
 10593  10619     int nModuleArg;      /* Number of arguments to the module */
................................................................................
 10691  10717   #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
 10692  10718   
 10693  10719   #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
 10694  10720   #define OE_SetNull  7   /* Set the foreign key value to NULL */
 10695  10721   #define OE_SetDflt  8   /* Set the foreign key value to its default */
 10696  10722   #define OE_Cascade  9   /* Cascade the changes */
 10697  10723   
 10698         -#define OE_Default  99  /* Do whatever the default action is */
        10724  +#define OE_Default  10  /* Do whatever the default action is */
 10699  10725   
 10700  10726   
 10701  10727   /*
 10702  10728   ** An instance of the following structure is passed as the first
 10703  10729   ** argument to sqlite3VdbeKeyCompare and is used to control the 
 10704  10730   ** comparison of the two index keys.
 10705  10731   **
................................................................................
 10778  10804     char *zColAff;           /* String defining the affinity of each column */
 10779  10805     Index *pNext;            /* The next index associated with the same table */
 10780  10806     Schema *pSchema;         /* Schema containing this index */
 10781  10807     u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
 10782  10808     char **azColl;           /* Array of collation sequence names for index */
 10783  10809     Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
 10784  10810     int tnum;                /* DB Page containing root of this index */
        10811  +  LogEst szIdxRow;         /* Estimated average row size in bytes */
 10785  10812     u16 nColumn;             /* Number of columns in table used by this index */
 10786  10813     u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
 10787  10814     unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
 10788  10815     unsigned bUnordered:1;   /* Use this index for == or IN queries only */
 10789  10816     unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
 10790  10817   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 10791  10818     int nSample;             /* Number of elements in aSample[] */
................................................................................
 10942  10969   ** are contained within the same memory allocation.  Note, however, that
 10943  10970   ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
 10944  10971   ** allocated, regardless of whether or not EP_Reduced is set.
 10945  10972   */
 10946  10973   struct Expr {
 10947  10974     u8 op;                 /* Operation performed by this node */
 10948  10975     char affinity;         /* The affinity of the column or 0 if not a column */
 10949         -  u16 flags;             /* Various flags.  EP_* See below */
        10976  +  u32 flags;             /* Various flags.  EP_* See below */
 10950  10977     union {
 10951  10978       char *zToken;          /* Token value. Zero terminated and dequoted */
 10952  10979       int iValue;            /* Non-negative integer value if EP_IntValue */
 10953  10980     } u;
 10954  10981   
 10955  10982     /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
 10956  10983     ** space is allocated for the fields below this point. An attempt to
 10957  10984     ** access them will result in a segfault or malfunction. 
 10958  10985     *********************************************************************/
 10959  10986   
 10960  10987     Expr *pLeft;           /* Left subnode */
 10961  10988     Expr *pRight;          /* Right subnode */
 10962  10989     union {
 10963         -    ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
 10964         -    Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
        10990  +    ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
        10991  +    Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
 10965  10992     } x;
 10966  10993   
 10967  10994     /* If the EP_Reduced flag is set in the Expr.flags mask, then no
 10968  10995     ** space is allocated for the fields below this point. An attempt to
 10969  10996     ** access them will result in a segfault or malfunction.
 10970  10997     *********************************************************************/
 10971  10998   
 10972  10999   #if SQLITE_MAX_EXPR_DEPTH>0
 10973  11000     int nHeight;           /* Height of the tree headed by this node */
 10974  11001   #endif
 10975  11002     int iTable;            /* TK_COLUMN: cursor number of table holding column
 10976  11003                            ** TK_REGISTER: register number
 10977         -                         ** TK_TRIGGER: 1 -> new, 0 -> old */
        11004  +                         ** TK_TRIGGER: 1 -> new, 0 -> old
        11005  +                         ** EP_Unlikely:  1000 times likelihood */
 10978  11006     ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
 10979  11007                            ** TK_VARIABLE: variable number (always >= 1). */
 10980  11008     i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
 10981  11009     i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
 10982         -  u8 flags2;             /* Second set of flags.  EP2_... */
 10983  11010     u8 op2;                /* TK_REGISTER: original value of Expr.op
 10984  11011                            ** TK_COLUMN: the value of p5 for OP_Column
 10985  11012                            ** TK_AGG_FUNCTION: nesting depth */
 10986  11013     AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
 10987  11014     Table *pTab;           /* Table for TK_COLUMN expressions. */
 10988  11015   };
 10989  11016   
 10990  11017   /*
 10991  11018   ** The following are the meanings of bits in the Expr.flags field.
 10992  11019   */
 10993         -#define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
 10994         -#define EP_Agg        0x0002  /* Contains one or more aggregate functions */
 10995         -#define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
 10996         -#define EP_Error      0x0008  /* Expression contains one or more errors */
 10997         -#define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
 10998         -#define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
 10999         -#define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
 11000         -#define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
 11001         -#define EP_Collate    0x0100  /* Tree contains a TK_COLLATE opeartor */
 11002         -#define EP_FixedDest  0x0200  /* Result needed in a specific register */
 11003         -#define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
 11004         -#define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
 11005         -#define EP_Hint       0x1000  /* Not used */
 11006         -#define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
 11007         -#define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
 11008         -#define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
 11009         -
 11010         -/*
 11011         -** The following are the meanings of bits in the Expr.flags2 field.
 11012         -*/
 11013         -#define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
 11014         -#define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
 11015         -
 11016         -/*
 11017         -** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
 11018         -** flag on an expression structure.  This flag is used for VV&A only.  The
 11019         -** routine is implemented as a macro that only works when in debugging mode,
 11020         -** so as not to burden production code.
 11021         -*/
 11022         -#ifdef SQLITE_DEBUG
 11023         -# define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
 11024         -#else
 11025         -# define ExprSetIrreducible(X)
 11026         -#endif
        11020  +#define EP_FromJoin  0x000001 /* Originated in ON or USING clause of a join */
        11021  +#define EP_Agg       0x000002 /* Contains one or more aggregate functions */
        11022  +#define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
        11023  +#define EP_Error     0x000008 /* Expression contains one or more errors */
        11024  +#define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
        11025  +#define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
        11026  +#define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
        11027  +#define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
        11028  +#define EP_Collate   0x000100 /* Tree contains a TK_COLLATE opeartor */
        11029  +#define EP_FixedDest 0x000200 /* Result needed in a specific register */
        11030  +#define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
        11031  +#define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
        11032  +#define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
        11033  +#define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
        11034  +#define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
        11035  +#define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
        11036  +#define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
        11037  +#define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
        11038  +#define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
 11027  11039   
 11028  11040   /*
 11029  11041   ** These macros can be used to test, set, or clear bits in the 
 11030  11042   ** Expr.flags field.
 11031  11043   */
 11032         -#define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
 11033         -#define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
        11044  +#define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
        11045  +#define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
 11034  11046   #define ExprSetProperty(E,P)     (E)->flags|=(P)
 11035  11047   #define ExprClearProperty(E,P)   (E)->flags&=~(P)
        11048  +
        11049  +/* The ExprSetVVAProperty() macro is used for Verification, Validation,
        11050  +** and Accreditation only.  It works like ExprSetProperty() during VVA
        11051  +** processes but is a no-op for delivery.
        11052  +*/
        11053  +#ifdef SQLITE_DEBUG
        11054  +# define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
        11055  +#else
        11056  +# define ExprSetVVAProperty(E,P)
        11057  +#endif
 11036  11058   
 11037  11059   /*
 11038  11060   ** Macros to determine the number of bytes required by a normal Expr 
 11039  11061   ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
 11040  11062   ** and an Expr struct with the EP_TokenOnly flag set.
 11041  11063   */
 11042  11064   #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
................................................................................
 11638  11660   ** routines as they walk the parse tree to make database references
 11639  11661   ** explicit.  
 11640  11662   */
 11641  11663   typedef struct DbFixer DbFixer;
 11642  11664   struct DbFixer {
 11643  11665     Parse *pParse;      /* The parsing context.  Error messages written here */
 11644  11666     Schema *pSchema;    /* Fix items to this schema */
        11667  +  int bVarOnly;       /* Check for variable references only */
 11645  11668     const char *zDb;    /* Make sure all objects are contained in this database */
 11646  11669     const char *zType;  /* Type of the container - used for error messages */
 11647  11670     const Token *pName; /* Name of the container - used for error messages */
 11648  11671   };
 11649  11672   
 11650  11673   /*
 11651  11674   ** An objected used to accumulate the text of a string where we
................................................................................
 12176  12199   # define sqlite3AuthRead(a,b,c,d)
 12177  12200   # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
 12178  12201   # define sqlite3AuthContextPush(a,b,c)
 12179  12202   # define sqlite3AuthContextPop(a)  ((void)(a))
 12180  12203   #endif
 12181  12204   SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
 12182  12205   SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
 12183         -SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
        12206  +SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
 12184  12207   SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
 12185  12208   SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
 12186  12209   SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
 12187  12210   SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
 12188  12211   SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
 12189  12212   SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
 12190  12213   SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
 12191  12214   SQLITE_PRIVATE int sqlite3Atoi(const char*);
 12192  12215   SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
 12193  12216   SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
 12194  12217   SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
        12218  +SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
        12219  +SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
        12220  +#ifndef SQLITE_OMIT_VIRTUALTABLE
        12221  +SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
        12222  +#endif
        12223  +SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
 12195  12224   
 12196  12225   /*
 12197  12226   ** Routines to read and write variable-length integers.  These used to
 12198  12227   ** be defined locally, but now we use the varint routines in the util.c
 12199  12228   ** file.  Code should use the MACRO forms below, as the Varint32 versions
 12200  12229   ** are coded to assume the single byte case is already handled (which 
 12201  12230   ** the MACRO form does).
................................................................................
 12304  12333   SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
 12305  12334   SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
 12306  12335   SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
 12307  12336   SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
 12308  12337   SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
 12309  12338   SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
 12310  12339   SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
 12311         -SQLITE_PRIVATE char sqlite3AffinityType(const char*);
        12340  +SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
 12312  12341   SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
 12313  12342   SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
 12314  12343   SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
 12315  12344   SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
 12316  12345   SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
 12317  12346   SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
 12318  12347   SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
................................................................................
 12408  12437   SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
 12409  12438   SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
 12410  12439   SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
 12411  12440   SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
 12412  12441   SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
 12413  12442   SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
 12414  12443   SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
        12444  +SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
 12415  12445   SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
 12416  12446   SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
 12417  12447   SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
 12418  12448   SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
 12419  12449   SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
 12420  12450   SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
 12421  12451   SQLITE_PRIVATE const char *sqlite3JournalModename(int);
................................................................................
 13586  13616     yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
 13587  13617     yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
 13588  13618     int iStatement;         /* Statement number (or 0 if has not opened stmt) */
 13589  13619     u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
 13590  13620   #ifndef SQLITE_OMIT_TRACE
 13591  13621     i64 startTime;          /* Time when query started - used for profiling */
 13592  13622   #endif
        13623  +  i64 iCurrentTime;       /* Value of julianday('now') for this statement */
 13593  13624     i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
 13594  13625     i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
 13595  13626     i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
 13596  13627     char *zSql;             /* Text of the SQL statement that generated this */
 13597  13628     void *pFree;            /* Free this when deleting the vdbe */
 13598  13629   #ifdef SQLITE_DEBUG
 13599  13630     FILE *trace;            /* Write an execution trace here, if not NULL */
................................................................................
 14265  14296   
 14266  14297   /*
 14267  14298   ** Set the time to the current time reported by the VFS.
 14268  14299   **
 14269  14300   ** Return the number of errors.
 14270  14301   */
 14271  14302   static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
 14272         -  sqlite3 *db = sqlite3_context_db_handle(context);
 14273         -  if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
        14303  +  p->iJD = sqlite3StmtCurrentTime(context);
        14304  +  if( p->iJD>0 ){
 14274  14305       p->validJD = 1;
 14275  14306       return 0;
 14276  14307     }else{
 14277  14308       return 1;
 14278  14309     }
 14279  14310   }
 14280  14311   
................................................................................
 14397  14428   ** The following routine implements the rough equivalent of localtime_r()
 14398  14429   ** using whatever operating-system specific localtime facility that
 14399  14430   ** is available.  This routine returns 0 on success and
 14400  14431   ** non-zero on any kind of error.
 14401  14432   **
 14402  14433   ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
 14403  14434   ** routine will always fail.
        14435  +**
        14436  +** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
        14437  +** library function localtime_r() is used to assist in the calculation of
        14438  +** local time.
 14404  14439   */
 14405  14440   static int osLocaltime(time_t *t, struct tm *pTm){
 14406  14441     int rc;
 14407  14442   #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
 14408  14443         && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
 14409  14444     struct tm *pX;
 14410  14445   #if SQLITE_THREADSAFE>0
................................................................................
 14453  14488   
 14454  14489     /* Initialize the contents of sLocal to avoid a compiler warning. */
 14455  14490     memset(&sLocal, 0, sizeof(sLocal));
 14456  14491   
 14457  14492     x = *p;
 14458  14493     computeYMD_HMS(&x);
 14459  14494     if( x.Y<1971 || x.Y>=2038 ){
        14495  +    /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
        14496  +    ** works for years between 1970 and 2037. For dates outside this range,
        14497  +    ** SQLite attempts to map the year into an equivalent year within this
        14498  +    ** range, do the calculation, then map the year back.
        14499  +    */
 14460  14500       x.Y = 2000;
 14461  14501       x.M = 1;
 14462  14502       x.D = 1;
 14463  14503       x.h = 0;
 14464  14504       x.m = 0;
 14465  14505       x.s = 0.0;
 14466  14506     } else {
................................................................................
 15049  15089     struct tm *pTm;
 15050  15090     struct tm sNow;
 15051  15091     char zBuf[20];
 15052  15092   
 15053  15093     UNUSED_PARAMETER(argc);
 15054  15094     UNUSED_PARAMETER(argv);
 15055  15095   
 15056         -  db = sqlite3_context_db_handle(context);
 15057         -  if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
        15096  +  iT = sqlite3StmtCurrentTime(context);
        15097  +  if( iT<=0 ) return;
 15058  15098     t = iT/1000 - 10000*(sqlite3_int64)21086676;
 15059  15099   #ifdef HAVE_GMTIME_R
 15060  15100     pTm = gmtime_r(&t, &sNow);
 15061  15101   #else
 15062  15102     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
 15063  15103     pTm = gmtime(&t);
 15064  15104     if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
................................................................................
 19256  19296   
 19257  19297   /*
 19258  19298   ** Free memory that might be associated with a particular database
 19259  19299   ** connection.
 19260  19300   */
 19261  19301   SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
 19262  19302     assert( db==0 || sqlite3_mutex_held(db->mutex) );
        19303  +  if( p==0 ) return;
 19263  19304     if( db ){
 19264  19305       if( db->pnBytesFreed ){
 19265  19306         *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
 19266  19307         return;
 19267  19308       }
 19268  19309       if( isLookaside(db, p) ){
 19269  19310         LookasideSlot *pBuf = (LookasideSlot*)p;
................................................................................
 21371  21412     switch( quote ){
 21372  21413       case '\'':  break;
 21373  21414       case '"':   break;
 21374  21415       case '`':   break;                /* For MySQL compatibility */
 21375  21416       case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
 21376  21417       default:    return -1;
 21377  21418     }
 21378         -  for(i=1, j=0; ALWAYS(z[i]); i++){
        21419  +  for(i=1, j=0;; i++){
        21420  +    assert( z[i] );
 21379  21421       if( z[i]==quote ){
 21380  21422         if( z[i+1]==quote ){
 21381  21423           z[j++] = quote;
 21382  21424           i++;
 21383  21425         }else{
 21384  21426           break;
 21385  21427         }
................................................................................
 22385  22427       int i, sz;
 22386  22428       sz = sqlite3Strlen30(z);
 22387  22429       for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
 22388  22430       if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
 22389  22431     }
 22390  22432   }
 22391  22433   #endif
        22434  +
        22435  +/* 
        22436  +** Find (an approximate) sum of two LogEst values.  This computation is
        22437  +** not a simple "+" operator because LogEst is stored as a logarithmic
        22438  +** value.
        22439  +** 
        22440  +*/
        22441  +SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
        22442  +  static const unsigned char x[] = {
        22443  +     10, 10,                         /* 0,1 */
        22444  +      9, 9,                          /* 2,3 */
        22445  +      8, 8,                          /* 4,5 */
        22446  +      7, 7, 7,                       /* 6,7,8 */
        22447  +      6, 6, 6,                       /* 9,10,11 */
        22448  +      5, 5, 5,                       /* 12-14 */
        22449  +      4, 4, 4, 4,                    /* 15-18 */
        22450  +      3, 3, 3, 3, 3, 3,              /* 19-24 */
        22451  +      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
        22452  +  };
        22453  +  if( a>=b ){
        22454  +    if( a>b+49 ) return a;
        22455  +    if( a>b+31 ) return a+1;
        22456  +    return a+x[a-b];
        22457  +  }else{
        22458  +    if( b>a+49 ) return b;
        22459  +    if( b>a+31 ) return b+1;
        22460  +    return b+x[b-a];
        22461  +  }
        22462  +}
        22463  +
        22464  +/*
        22465  +** Convert an integer into a LogEst.  In other words, compute a
        22466  +** good approximatation for 10*log2(x).
        22467  +*/
        22468  +SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
        22469  +  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
        22470  +  LogEst y = 40;
        22471  +  if( x<8 ){
        22472  +    if( x<2 ) return 0;
        22473  +    while( x<8 ){  y -= 10; x <<= 1; }
        22474  +  }else{
        22475  +    while( x>255 ){ y += 40; x >>= 4; }
        22476  +    while( x>15 ){  y += 10; x >>= 1; }
        22477  +  }
        22478  +  return a[x&7] + y - 10;
        22479  +}
        22480  +
        22481  +#ifndef SQLITE_OMIT_VIRTUALTABLE
        22482  +/*
        22483  +** Convert a double into a LogEst
        22484  +** In other words, compute an approximation for 10*log2(x).
        22485  +*/
        22486  +SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
        22487  +  u64 a;
        22488  +  LogEst e;
        22489  +  assert( sizeof(x)==8 && sizeof(a)==8 );
        22490  +  if( x<=1 ) return 0;
        22491  +  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
        22492  +  memcpy(&a, &x, 8);
        22493  +  e = (a>>52) - 1022;
        22494  +  return e*10;
        22495  +}
        22496  +#endif /* SQLITE_OMIT_VIRTUALTABLE */
        22497  +
        22498  +/*
        22499  +** Convert a LogEst into an integer.
        22500  +*/
        22501  +SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
        22502  +  u64 n;
        22503  +  if( x<10 ) return 1;
        22504  +  n = x%10;
        22505  +  x /= 10;
        22506  +  if( n>=5 ) n -= 2;
        22507  +  else if( n>=1 ) n -= 1;
        22508  +  if( x>=3 ) return (n+8)<<(x-3);
        22509  +  return (n+8)>>(3-x);
        22510  +}
 22392  22511   
 22393  22512   /************** End of util.c ************************************************/
 22394  22513   /************** Begin file hash.c ********************************************/
 22395  22514   /*
 22396  22515   ** 2001 September 22
 22397  22516   **
 22398  22517   ** The author disclaims copyright to this source code.  In place of
................................................................................
 31379  31498     { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
 31380  31499   #else
 31381  31500     { "GetVersionExA",           (SYSCALL)0,                       0 },
 31382  31501   #endif
 31383  31502   
 31384  31503   #define osGetVersionExA ((BOOL(WINAPI*)( \
 31385  31504           LPOSVERSIONINFOA))aSyscall[34].pCurrent)
        31505  +
        31506  +#if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
        31507  +  { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
        31508  +#else
        31509  +  { "GetVersionExW",           (SYSCALL)0,                       0 },
        31510  +#endif
        31511  +
        31512  +#define osGetVersionExW ((BOOL(WINAPI*)( \
        31513  +        LPOSVERSIONINFOW))aSyscall[35].pCurrent)
 31386  31514   
 31387  31515     { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
 31388  31516   
 31389  31517   #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
 31390         -        SIZE_T))aSyscall[35].pCurrent)
        31518  +        SIZE_T))aSyscall[36].pCurrent)
 31391  31519   
 31392  31520   #if !SQLITE_OS_WINRT
 31393  31521     { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
 31394  31522   #else
 31395  31523     { "HeapCreate",              (SYSCALL)0,                       0 },
 31396  31524   #endif
 31397  31525   
 31398  31526   #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
 31399         -        SIZE_T))aSyscall[36].pCurrent)
        31527  +        SIZE_T))aSyscall[37].pCurrent)
 31400  31528   
 31401  31529   #if !SQLITE_OS_WINRT
 31402  31530     { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
 31403  31531   #else
 31404  31532     { "HeapDestroy",             (SYSCALL)0,                       0 },
 31405  31533   #endif
 31406  31534   
 31407         -#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
        31535  +#define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
 31408  31536   
 31409  31537     { "HeapFree",                (SYSCALL)HeapFree,                0 },
 31410  31538   
 31411         -#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
        31539  +#define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
 31412  31540   
 31413  31541     { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
 31414  31542   
 31415  31543   #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
 31416         -        SIZE_T))aSyscall[39].pCurrent)
        31544  +        SIZE_T))aSyscall[40].pCurrent)
 31417  31545   
 31418  31546     { "HeapSize",                (SYSCALL)HeapSize,                0 },
 31419  31547   
 31420  31548   #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
 31421         -        LPCVOID))aSyscall[40].pCurrent)
        31549  +        LPCVOID))aSyscall[41].pCurrent)
 31422  31550   
 31423  31551   #if !SQLITE_OS_WINRT
 31424  31552     { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
 31425  31553   #else
 31426  31554     { "HeapValidate",            (SYSCALL)0,                       0 },
 31427  31555   #endif
 31428  31556   
 31429  31557   #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
 31430         -        LPCVOID))aSyscall[41].pCurrent)
        31558  +        LPCVOID))aSyscall[42].pCurrent)
 31431  31559   
 31432  31560   #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
 31433  31561     { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
 31434  31562   #else
 31435  31563     { "LoadLibraryA",            (SYSCALL)0,                       0 },
 31436  31564   #endif
 31437  31565   
 31438         -#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
        31566  +#define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[43].pCurrent)
 31439  31567   
 31440  31568   #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
 31441  31569           !defined(SQLITE_OMIT_LOAD_EXTENSION)
 31442  31570     { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
 31443  31571   #else
 31444  31572     { "LoadLibraryW",            (SYSCALL)0,                       0 },
 31445  31573   #endif
 31446  31574   
 31447         -#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
        31575  +#define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[44].pCurrent)
 31448  31576   
 31449  31577   #if !SQLITE_OS_WINRT
 31450  31578     { "LocalFree",               (SYSCALL)LocalFree,               0 },
 31451  31579   #else
 31452  31580     { "LocalFree",               (SYSCALL)0,                       0 },
 31453  31581   #endif
 31454  31582   
 31455         -#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
        31583  +#define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[45].pCurrent)
 31456  31584   
 31457  31585   #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 31458  31586     { "LockFile",                (SYSCALL)LockFile,                0 },
 31459  31587   #else
 31460  31588     { "LockFile",                (SYSCALL)0,                       0 },
 31461  31589   #endif
 31462  31590   
 31463  31591   #ifndef osLockFile
 31464  31592   #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 31465         -        DWORD))aSyscall[45].pCurrent)
        31593  +        DWORD))aSyscall[46].pCurrent)
 31466  31594   #endif
 31467  31595   
 31468  31596   #if !SQLITE_OS_WINCE
 31469  31597     { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
 31470  31598   #else
 31471  31599     { "LockFileEx",              (SYSCALL)0,                       0 },
 31472  31600   #endif
 31473  31601   
 31474  31602   #ifndef osLockFileEx
 31475  31603   #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
 31476         -        LPOVERLAPPED))aSyscall[46].pCurrent)
        31604  +        LPOVERLAPPED))aSyscall[47].pCurrent)
 31477  31605   #endif
 31478  31606   
 31479  31607   #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
 31480  31608     { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
 31481  31609   #else
 31482  31610     { "MapViewOfFile",           (SYSCALL)0,                       0 },
 31483  31611   #endif
 31484  31612   
 31485  31613   #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 31486         -        SIZE_T))aSyscall[47].pCurrent)
        31614  +        SIZE_T))aSyscall[48].pCurrent)
 31487  31615   
 31488  31616     { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
 31489  31617   
 31490  31618   #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
 31491         -        int))aSyscall[48].pCurrent)
        31619  +        int))aSyscall[49].pCurrent)
 31492  31620   
 31493  31621     { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
 31494  31622   
 31495  31623   #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
 31496         -        LARGE_INTEGER*))aSyscall[49].pCurrent)
        31624  +        LARGE_INTEGER*))aSyscall[50].pCurrent)
 31497  31625   
 31498  31626     { "ReadFile",                (SYSCALL)ReadFile,                0 },
 31499  31627   
 31500  31628   #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
 31501         -        LPOVERLAPPED))aSyscall[50].pCurrent)
        31629  +        LPOVERLAPPED))aSyscall[51].pCurrent)
 31502  31630   
 31503  31631     { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
 31504  31632   
 31505         -#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
        31633  +#define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent)
 31506  31634   
 31507  31635   #if !SQLITE_OS_WINRT
 31508  31636     { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
 31509  31637   #else
 31510  31638     { "SetFilePointer",          (SYSCALL)0,                       0 },
 31511  31639   #endif
 31512  31640   
 31513  31641   #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
 31514         -        DWORD))aSyscall[52].pCurrent)
        31642  +        DWORD))aSyscall[53].pCurrent)
 31515  31643   
 31516  31644   #if !SQLITE_OS_WINRT
 31517  31645     { "Sleep",                   (SYSCALL)Sleep,                   0 },
 31518  31646   #else
 31519  31647     { "Sleep",                   (SYSCALL)0,                       0 },
 31520  31648   #endif
 31521  31649   
 31522         -#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
        31650  +#define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[54].pCurrent)
 31523  31651   
 31524  31652     { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
 31525  31653   
 31526  31654   #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
 31527         -        LPFILETIME))aSyscall[54].pCurrent)
        31655  +        LPFILETIME))aSyscall[55].pCurrent)
 31528  31656   
 31529  31657   #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
 31530  31658     { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
 31531  31659   #else
 31532  31660     { "UnlockFile",              (SYSCALL)0,                       0 },
 31533  31661   #endif
 31534  31662   
 31535  31663   #ifndef osUnlockFile
 31536  31664   #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 31537         -        DWORD))aSyscall[55].pCurrent)
        31665  +        DWORD))aSyscall[56].pCurrent)
 31538  31666   #endif
 31539  31667   
 31540  31668   #if !SQLITE_OS_WINCE
 31541  31669     { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
 31542  31670   #else
 31543  31671     { "UnlockFileEx",            (SYSCALL)0,                       0 },
 31544  31672   #endif
 31545  31673   
 31546  31674   #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
 31547         -        LPOVERLAPPED))aSyscall[56].pCurrent)
        31675  +        LPOVERLAPPED))aSyscall[57].pCurrent)
 31548  31676   
 31549  31677   #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
 31550  31678     { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
 31551  31679   #else
 31552  31680     { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
 31553  31681   #endif
 31554  31682   
 31555         -#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
        31683  +#define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[58].pCurrent)
 31556  31684   
 31557  31685     { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
 31558  31686   
 31559  31687   #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
 31560         -        LPCSTR,LPBOOL))aSyscall[58].pCurrent)
        31688  +        LPCSTR,LPBOOL))aSyscall[59].pCurrent)
 31561  31689   
 31562  31690     { "WriteFile",               (SYSCALL)WriteFile,               0 },
 31563  31691   
 31564  31692   #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
 31565         -        LPOVERLAPPED))aSyscall[59].pCurrent)
        31693  +        LPOVERLAPPED))aSyscall[60].pCurrent)
 31566  31694   
 31567  31695   #if SQLITE_OS_WINRT
 31568  31696     { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
 31569  31697   #else
 31570  31698     { "CreateEventExW",          (SYSCALL)0,                       0 },
 31571  31699   #endif
 31572  31700   
 31573  31701   #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
 31574         -        DWORD,DWORD))aSyscall[60].pCurrent)
        31702  +        DWORD,DWORD))aSyscall[61].pCurrent)
 31575  31703   
 31576  31704   #if !SQLITE_OS_WINRT
 31577  31705     { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
 31578  31706   #else
 31579  31707     { "WaitForSingleObject",     (SYSCALL)0,                       0 },
 31580  31708   #endif
 31581  31709   
 31582  31710   #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
 31583         -        DWORD))aSyscall[61].pCurrent)
        31711  +        DWORD))aSyscall[62].pCurrent)
 31584  31712   
 31585  31713   #if SQLITE_OS_WINRT
 31586  31714     { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
 31587  31715   #else
 31588  31716     { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
 31589  31717   #endif
 31590  31718   
 31591  31719   #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
 31592         -        BOOL))aSyscall[62].pCurrent)
        31720  +        BOOL))aSyscall[63].pCurrent)
 31593  31721   
 31594  31722   #if SQLITE_OS_WINRT
 31595  31723     { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
 31596  31724   #else
 31597  31725     { "SetFilePointerEx",        (SYSCALL)0,                       0 },
 31598  31726   #endif
 31599  31727   
 31600  31728   #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
 31601         -        PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
        31729  +        PLARGE_INTEGER,DWORD))aSyscall[64].pCurrent)
 31602  31730   
 31603  31731   #if SQLITE_OS_WINRT
 31604  31732     { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
 31605  31733   #else
 31606  31734     { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
 31607  31735   #endif
 31608  31736   
 31609  31737   #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
 31610         -        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
        31738  +        FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[65].pCurrent)
 31611  31739   
 31612  31740   #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
 31613  31741     { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
 31614  31742   #else
 31615  31743     { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
 31616  31744   #endif
 31617  31745   
 31618  31746   #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
 31619         -        SIZE_T))aSyscall[65].pCurrent)
        31747  +        SIZE_T))aSyscall[66].pCurrent)
 31620  31748   
 31621  31749   #if SQLITE_OS_WINRT
 31622  31750     { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
 31623  31751   #else
 31624  31752     { "CreateFile2",             (SYSCALL)0,                       0 },
 31625  31753   #endif
 31626  31754   
 31627  31755   #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
 31628         -        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
        31756  +        LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[67].pCurrent)
 31629  31757   
 31630  31758   #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
 31631  31759     { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
 31632  31760   #else
 31633  31761     { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
 31634  31762   #endif
 31635  31763   
 31636  31764   #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
 31637         -        DWORD))aSyscall[67].pCurrent)
        31765  +        DWORD))aSyscall[68].pCurrent)
 31638  31766   
 31639  31767   #if SQLITE_OS_WINRT
 31640  31768     { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
 31641  31769   #else
 31642  31770     { "GetTickCount64",          (SYSCALL)0,                       0 },
 31643  31771   #endif
 31644  31772   
 31645         -#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
        31773  +#define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[69].pCurrent)
 31646  31774   
 31647  31775   #if SQLITE_OS_WINRT
 31648  31776     { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
 31649  31777   #else
 31650  31778     { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
 31651  31779   #endif
 31652  31780   
 31653  31781   #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
 31654         -        LPSYSTEM_INFO))aSyscall[69].pCurrent)
        31782  +        LPSYSTEM_INFO))aSyscall[70].pCurrent)
 31655  31783   
 31656  31784   #if defined(SQLITE_WIN32_HAS_ANSI)
 31657  31785     { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
 31658  31786   #else
 31659  31787     { "OutputDebugStringA",      (SYSCALL)0,                       0 },
 31660  31788   #endif
 31661  31789   
 31662         -#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
        31790  +#define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[71].pCurrent)
 31663  31791   
 31664  31792   #if defined(SQLITE_WIN32_HAS_WIDE)
 31665  31793     { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
 31666  31794   #else
 31667  31795     { "OutputDebugStringW",      (SYSCALL)0,                       0 },
 31668  31796   #endif
 31669  31797   
 31670         -#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
        31798  +#define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[72].pCurrent)
 31671  31799   
 31672  31800     { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
 31673  31801   
 31674         -#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
        31802  +#define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[73].pCurrent)
 31675  31803   
 31676  31804   #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
 31677  31805     { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
 31678  31806   #else
 31679  31807     { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
 31680  31808   #endif
 31681  31809   
 31682  31810   #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
 31683         -        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
        31811  +        LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[74].pCurrent)
 31684  31812   
 31685  31813   }; /* End of the overrideable system calls */
 31686  31814   
 31687  31815   /*
 31688  31816   ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
 31689  31817   ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
 31690  31818   ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
................................................................................
 31832  31960   ** Here is an interesting observation:  Win95, Win98, and WinME lack
 31833  31961   ** the LockFileEx() API.  But we can still statically link against that
 31834  31962   ** API as long as we don't call it when running Win95/98/ME.  A call to
 31835  31963   ** this routine is used to determine if the host is Win95/98/ME or
 31836  31964   ** WinNT/2K/XP so that we will know whether or not we can safely call
 31837  31965   ** the LockFileEx() API.
 31838  31966   */
        31967  +#ifndef NTDDI_WIN8
        31968  +#  define NTDDI_WIN8                        0x06020000
        31969  +#endif
        31970  +
 31839  31971   #if SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
 31840  31972   # define osIsNT()  (1)
 31841  31973   #elif !defined(SQLITE_WIN32_HAS_WIDE)
 31842  31974   # define osIsNT()  (0)
 31843  31975   #else
 31844  31976     static int osIsNT(void){
 31845  31977       if( sqlite3_os_type==0 ){
        31978  +#if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
        31979  +      OSVERSIONINFOW sInfo;
        31980  +      sInfo.dwOSVersionInfoSize = sizeof(sInfo);
        31981  +      osGetVersionExW(&sInfo);
        31982  +#else
 31846  31983         OSVERSIONINFOA sInfo;
 31847  31984         sInfo.dwOSVersionInfoSize = sizeof(sInfo);
 31848  31985         osGetVersionExA(&sInfo);
        31986  +#endif
 31849  31987         sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
 31850  31988       }
 31851  31989       return sqlite3_os_type==2;
 31852  31990     }
 31853  31991   #endif
 31854  31992   
 31855  31993   #ifdef SQLITE_WIN32_MALLOC
................................................................................
 35864  36002       winGetSystemCall,    /* xGetSystemCall */
 35865  36003       winNextSystemCall,   /* xNextSystemCall */
 35866  36004     };
 35867  36005   #endif
 35868  36006   
 35869  36007     /* Double-check that the aSyscall[] array has been constructed
 35870  36008     ** correctly.  See ticket [bb3a86e890c8e96ab] */
 35871         -  assert( ArraySize(aSyscall)==74 );
        36009  +  assert( ArraySize(aSyscall)==75 );
 35872  36010   
 35873  36011     /* get memory map allocation granularity */
 35874  36012     memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
 35875  36013   #if SQLITE_OS_WINRT
 35876  36014     osGetNativeSystemInfo(&winSysInfo);
 35877  36015   #else
 35878  36016     osGetSystemInfo(&winSysInfo);
................................................................................
 48965  49103   **
 48966  49104   ** The first page is always a btree page.  The first 100 bytes of the first
 48967  49105   ** page contain a special header (the "file header") that describes the file.
 48968  49106   ** The format of the file header is as follows:
 48969  49107   **
 48970  49108   **   OFFSET   SIZE    DESCRIPTION
 48971  49109   **      0      16     Header string: "SQLite format 3\000"
 48972         -**     16       2     Page size in bytes.  
        49110  +**     16       2     Page size in bytes.  (1 means 65536)
 48973  49111   **     18       1     File format write version
 48974  49112   **     19       1     File format read version
 48975  49113   **     20       1     Bytes of unused space at the end of each page
 48976         -**     21       1     Max embedded payload fraction
 48977         -**     22       1     Min embedded payload fraction
 48978         -**     23       1     Min leaf payload fraction
        49114  +**     21       1     Max embedded payload fraction (must be 64)
        49115  +**     22       1     Min embedded payload fraction (must be 32)
        49116  +**     23       1     Min leaf payload fraction (must be 32)
 48979  49117   **     24       4     File change counter
 48980  49118   **     28       4     Reserved for future use
 48981  49119   **     32       4     First freelist page
 48982  49120   **     36       4     Number of freelist pages in the file
 48983  49121   **     40      60     15 4-byte meta values passed to higher layers
 48984  49122   **
 48985  49123   **     40       4     Schema cookie
 48986  49124   **     44       4     File format of schema layer
 48987  49125   **     48       4     Size of page cache
 48988  49126   **     52       4     Largest root-page (auto/incr_vacuum)
 48989  49127   **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
 48990  49128   **     60       4     User version
 48991  49129   **     64       4     Incremental vacuum mode
 48992         -**     68       4     unused
 48993         -**     72       4     unused
 48994         -**     76       4     unused
        49130  +**     68       4     Application-ID
        49131  +**     72      20     unused
        49132  +**     92       4     The version-valid-for number
        49133  +**     96       4     SQLITE_VERSION_NUMBER
 48995  49134   **
 48996  49135   ** All of the integer values are big-endian (most significant byte first).
 48997  49136   **
 48998  49137   ** The file change counter is incremented when the database is changed
 48999  49138   ** This counter allows other processes to know when the file has changed
 49000  49139   ** and thus when they need to flush their cache.
 49001  49140   **
................................................................................
 52357  52496       pBt->max1bytePayload = 127;
 52358  52497     }else{
 52359  52498       pBt->max1bytePayload = (u8)pBt->maxLocal;
 52360  52499     }
 52361  52500     assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
 52362  52501     pBt->pPage1 = pPage1;
 52363  52502     pBt->nPage = nPage;
 52364         -assert( pPage1->leaf==0 || pPage1->leaf==1 );
 52365  52503     return SQLITE_OK;
 52366  52504   
 52367  52505   page1_init_failed:
 52368  52506     releasePage(pPage1);
 52369  52507     pBt->pPage1 = 0;
 52370  52508     return rc;
 52371  52509   }
................................................................................
 52517  52655     /* If the btree is already in a write-transaction, or it
 52518  52656     ** is already in a read-transaction and a read-transaction
 52519  52657     ** is requested, this is a no-op.
 52520  52658     */
 52521  52659     if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
 52522  52660       goto trans_begun;
 52523  52661     }
 52524         -  assert( IfNotOmitAV(pBt->bDoTruncate)==0 );
        52662  +  assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
 52525  52663   
 52526  52664     /* Write transactions are not possible on a read-only database */
 52527  52665     if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
 52528  52666       rc = SQLITE_READONLY;
 52529  52667       goto trans_begun;
 52530  52668     }
 52531  52669   
................................................................................
 60168  60306         if( pRec==0 ) return 0;
 60169  60307         p->ppRec[0] = pRec;
 60170  60308       }
 60171  60309     
 60172  60310       pRec->nField = p->iVal+1;
 60173  60311       return &pRec->aMem[p->iVal];
 60174  60312     }
 60175         -#endif
        60313  +#else
        60314  +  UNUSED_PARAMETER(p);
        60315  +#endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
 60176  60316     return sqlite3ValueNew(db);
 60177  60317   }
 60178  60318   
 60179  60319   /*
 60180  60320   ** Extract a value from the supplied expression in the manner described
 60181  60321   ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
 60182  60322   ** using valueNew().
................................................................................
 60339  60479     int iSerial;                    /* Serial type */
 60340  60480     int nSerial;                    /* Bytes of space for iSerial as varint */
 60341  60481     int nVal;                       /* Bytes of space required for argv[0] */
 60342  60482     int nRet;
 60343  60483     sqlite3 *db;
 60344  60484     u8 *aRet;
 60345  60485   
        60486  +  UNUSED_PARAMETER( argc );
 60346  60487     iSerial = sqlite3VdbeSerialType(argv[0], file_format);
 60347  60488     nSerial = sqlite3VarintLen(iSerial);
 60348  60489     nVal = sqlite3VdbeSerialTypeLen(iSerial);
 60349  60490     db = sqlite3_context_db_handle(context);
 60350  60491   
 60351  60492     nRet = 1 + nSerial + nVal;
 60352  60493     aRet = sqlite3DbMallocRaw(db, nRet);
................................................................................
 62956  63097           );
 62957  63098           sqlite3VdbePrintOp(out, i, &p->aOp[i]);
 62958  63099         }
 62959  63100         fclose(out);
 62960  63101       }
 62961  63102     }
 62962  63103   #endif
        63104  +  p->iCurrentTime = 0;
 62963  63105     p->magic = VDBE_MAGIC_INIT;
 62964  63106     return p->rc & db->errMask;
 62965  63107   }
 62966  63108    
 62967  63109   /*
 62968  63110   ** Clean up and delete a VDBE after execution.  Return an integer which is
 62969  63111   ** the result code.  Write any error message text into *pzErrMsg.
................................................................................
 64351  64493         v->rc = rc = SQLITE_NOMEM;
 64352  64494       }
 64353  64495     }
 64354  64496     rc = sqlite3ApiExit(db, rc);
 64355  64497     sqlite3_mutex_leave(db->mutex);
 64356  64498     return rc;
 64357  64499   }
        64500  +
 64358  64501   
 64359  64502   /*
 64360  64503   ** Extract the user data from a sqlite3_context structure and return a
 64361  64504   ** pointer to it.
 64362  64505   */
 64363  64506   SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
 64364  64507     assert( p && p->pFunc );
................................................................................
 64375  64518   ** sqlite3_create_function16() routines that originally registered the
 64376  64519   ** application defined function.
 64377  64520   */
 64378  64521   SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
 64379  64522     assert( p && p->pFunc );
 64380  64523     return p->s.db;
 64381  64524   }
        64525  +
        64526  +/*
        64527  +** Return the current time for a statement
        64528  +*/
        64529  +SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
        64530  +  Vdbe *v = p->pVdbe;
        64531  +  int rc;
        64532  +  if( v->iCurrentTime==0 ){
        64533  +    rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
        64534  +    if( rc ) v->iCurrentTime = 0;
        64535  +  }
        64536  +  return v->iCurrentTime;
        64537  +}
 64382  64538   
 64383  64539   /*
 64384  64540   ** The following is the implementation of an SQL function that always
 64385  64541   ** fails with an error message stating that the function is used in the
 64386  64542   ** wrong context.  The sqlite3_overload_function() API might construct
 64387  64543   ** SQL function that use this routine so that the functions will exist
 64388  64544   ** for name resolution but are actually overloaded by the xFindFunction
................................................................................
 66528  66684       /* This happens if a malloc() inside a call to sqlite3_column_text() or
 66529  66685       ** sqlite3_column_text16() failed.  */
 66530  66686       goto no_mem;
 66531  66687     }
 66532  66688     assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
 66533  66689     assert( p->bIsReader || p->readOnly!=0 );
 66534  66690     p->rc = SQLITE_OK;
        66691  +  p->iCurrentTime = 0;
 66535  66692     assert( p->explain==0 );
 66536  66693     p->pResultSet = 0;
 66537  66694     db->busyHandler.nBusy = 0;
 66538  66695     CHECK_FOR_INTERRUPT;
 66539  66696     sqlite3VdbeIOTraceSql(p);
 66540  66697   #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
 66541  66698     if( db->xProgress ){
................................................................................
 74444  74601   SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
 74445  74602     int rc;
 74446  74603     if( pExpr==0 ) return WRC_Continue;
 74447  74604     testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
 74448  74605     testcase( ExprHasProperty(pExpr, EP_Reduced) );
 74449  74606     rc = pWalker->xExprCallback(pWalker, pExpr);
 74450  74607     if( rc==WRC_Continue
 74451         -              && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
        74608  +              && !ExprHasProperty(pExpr,EP_TokenOnly) ){
 74452  74609       if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
 74453  74610       if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
 74454  74611       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 74455  74612         if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
 74456  74613       }else{
 74457  74614         if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
 74458  74615       }
................................................................................
 74663  74820     db = pParse->db;
 74664  74821     pDup = sqlite3ExprDup(db, pOrig, 0);
 74665  74822     if( pDup==0 ) return;
 74666  74823     if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
 74667  74824       incrAggFunctionDepth(pDup, nSubquery);
 74668  74825       pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
 74669  74826       if( pDup==0 ) return;
        74827  +    ExprSetProperty(pDup, EP_Skip);
 74670  74828       if( pEList->a[iCol].iAlias==0 ){
 74671  74829         pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
 74672  74830       }
 74673  74831       pDup->iTable = pEList->a[iCol].iAlias;
 74674  74832     }
 74675  74833     if( pExpr->op==TK_COLLATE ){
 74676  74834       pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
................................................................................
 74685  74843     */
 74686  74844     ExprSetProperty(pExpr, EP_Static);
 74687  74845     sqlite3ExprDelete(db, pExpr);
 74688  74846     memcpy(pExpr, pDup, sizeof(*pExpr));
 74689  74847     if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
 74690  74848       assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
 74691  74849       pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
 74692         -    pExpr->flags2 |= EP2_MallocedToken;
        74850  +    pExpr->flags |= EP_MemToken;
 74693  74851     }
 74694  74852     sqlite3DbFree(db, pDup);
 74695  74853   }
 74696  74854   
 74697  74855   
 74698  74856   /*
 74699  74857   ** Return TRUE if the name zCol occurs anywhere in the USING clause.
................................................................................
 74785  74943     struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
 74786  74944     NameContext *pTopNC = pNC;        /* First namecontext in the list */
 74787  74945     Schema *pSchema = 0;              /* Schema of the expression */
 74788  74946     int isTrigger = 0;
 74789  74947   
 74790  74948     assert( pNC );     /* the name context cannot be NULL. */
 74791  74949     assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
 74792         -  assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
        74950  +  assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 74793  74951   
 74794  74952     /* Initialize the node to no-match */
 74795  74953     pExpr->iTable = -1;
 74796  74954     pExpr->pTab = 0;
 74797         -  ExprSetIrreducible(pExpr);
        74955  +  ExprSetVVAProperty(pExpr, EP_NoReduce);
 74798  74956   
 74799  74957     /* Translate the schema name in zDb into a pointer to the corresponding
 74800  74958     ** schema.  If not found, pSchema will remain NULL and nothing will match
 74801  74959     ** resulting in an appropriate error message toward the end of this routine
 74802  74960     */
 74803  74961     if( zDb ){
 74804  74962       testcase( pNC->ncFlags & NC_PartIdx );
................................................................................
 75126  75284       sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
 75127  75285     }
 75128  75286   }
 75129  75287   #else
 75130  75288   # define notValidCheckConstraint(P,N,M)
 75131  75289   #endif
 75132  75290   
        75291  +/*
        75292  +** Expression p should encode a floating point value between 1.0 and 0.0.
        75293  +** Return 1024 times this value.  Or return -1 if p is not a floating point
        75294  +** value between 1.0 and 0.0.
        75295  +*/
        75296  +static int exprProbability(Expr *p){
        75297  +  double r = -1.0;
        75298  +  if( p->op!=TK_FLOAT ) return -1;
        75299  +  sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
        75300  +  assert( r>=0.0 );
        75301  +  if( r>1.0 ) return -1;
        75302  +  return (int)(r*1000.0);
        75303  +}
 75133  75304   
 75134  75305   /*
 75135  75306   ** This routine is callback for sqlite3WalkExpr().
 75136  75307   **
 75137  75308   ** Resolve symbolic names into TK_COLUMN operators for the current
 75138  75309   ** node in the expression tree.  Return 0 to continue the search down
 75139  75310   ** the tree or 2 to abort the tree walk.
................................................................................
 75147  75318     Parse *pParse;
 75148  75319   
 75149  75320     pNC = pWalker->u.pNC;
 75150  75321     assert( pNC!=0 );
 75151  75322     pParse = pNC->pParse;
 75152  75323     assert( pParse==pWalker->pParse );
 75153  75324   
 75154         -  if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
        75325  +  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
 75155  75326     ExprSetProperty(pExpr, EP_Resolved);
 75156  75327   #ifndef NDEBUG
 75157  75328     if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
 75158  75329       SrcList *pSrcList = pNC->pSrcList;
 75159  75330       int i;
 75160  75331       for(i=0; i<pNC->pSrcList->nSrc; i++){
 75161  75332         assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
................................................................................
 75239  75410           if( pDef==0 ){
 75240  75411             no_such_func = 1;
 75241  75412           }else{
 75242  75413             wrong_num_args = 1;
 75243  75414           }
 75244  75415         }else{
 75245  75416           is_agg = pDef->xFunc==0;
        75417  +        if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
        75418  +          ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
        75419  +          if( n==2 ){
        75420  +            pExpr->iTable = exprProbability(pList->a[1].pExpr);
        75421  +            if( pExpr->iTable<0 ){
        75422  +              sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
        75423  +                                      "constant between 0.0 and 1.0");
        75424  +              pNC->nErr++;
        75425  +            }
        75426  +          }else{
        75427  +            /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
        75428  +            ** likelihood(X, 0.0625).
        75429  +            ** EVIDENCE-OF: R-35738-39582 The unlikely(X) fucntion is short-hand for
        75430  +            ** likelihood(X,0.0625). */
        75431  +            pExpr->iTable = 62;  /* TUNING:  Default 2nd arg to unlikely() is 0.0625 */
        75432  +          }             
        75433  +        }
 75246  75434         }
 75247  75435   #ifndef SQLITE_OMIT_AUTHORIZATION
 75248  75436         if( pDef ){
 75249  75437           auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
 75250  75438           if( auth!=SQLITE_OK ){
 75251  75439             if( auth==SQLITE_DENY ){
 75252  75440               sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
................................................................................
 76019  76207     if( op==TK_SELECT ){
 76020  76208       assert( pExpr->flags&EP_xIsSelect );
 76021  76209       return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
 76022  76210     }
 76023  76211   #ifndef SQLITE_OMIT_CAST
 76024  76212     if( op==TK_CAST ){
 76025  76213       assert( !ExprHasProperty(pExpr, EP_IntValue) );
 76026         -    return sqlite3AffinityType(pExpr->u.zToken);
        76214  +    return sqlite3AffinityType(pExpr->u.zToken, 0);
 76027  76215     }
 76028  76216   #endif
 76029  76217     if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
 76030  76218      && pExpr->pTab!=0
 76031  76219     ){
 76032  76220       /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
 76033  76221       ** a TK_COLUMN but was previously evaluated and cached in a register */
................................................................................
 76048  76236   ** and the pExpr parameter is returned unchanged.
 76049  76237   */
 76050  76238   SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
 76051  76239     if( pCollName->n>0 ){
 76052  76240       Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
 76053  76241       if( pNew ){
 76054  76242         pNew->pLeft = pExpr;
 76055         -      pNew->flags |= EP_Collate;
        76243  +      pNew->flags |= EP_Collate|EP_Skip;
 76056  76244         pExpr = pNew;
 76057  76245       }
 76058  76246     }
 76059  76247     return pExpr;
 76060  76248   }
 76061  76249   SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
 76062  76250     Token s;
................................................................................
 76063  76251     assert( zC!=0 );
 76064  76252     s.z = zC;
 76065  76253     s.n = sqlite3Strlen30(s.z);
 76066  76254     return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
 76067  76255   }
 76068  76256   
 76069  76257   /*
 76070         -** Skip over any TK_COLLATE and/or TK_AS operators at the root of
 76071         -** an expression.
        76258  +** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
        76259  +** or likelihood() function at the root of an expression.
 76072  76260   */
 76073  76261   SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
 76074         -  while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
 76075         -    pExpr = pExpr->pLeft;
 76076         -  }
        76262  +  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
        76263  +    if( ExprHasProperty(pExpr, EP_Unlikely) ){
        76264  +      assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
        76265  +      assert( pExpr->x.pList->nExpr>0 );
        76266  +      assert( pExpr->op==TK_FUNCTION );
        76267  +      pExpr = pExpr->x.pList->a[0].pExpr;
        76268  +    }else{
        76269  +      assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
        76270  +      pExpr = pExpr->pLeft;
        76271  +    }
        76272  +  }   
 76077  76273     return pExpr;
 76078  76274   }
 76079  76275   
 76080  76276   /*
 76081  76277   ** Return the collation sequence for the expression pExpr. If
 76082  76278   ** there is no defined collating sequence, return NULL.
 76083  76279   **
................................................................................
 76574  76770   ** assigned.
 76575  76771   */
 76576  76772   SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
 76577  76773     sqlite3 *db = pParse->db;
 76578  76774     const char *z;
 76579  76775   
 76580  76776     if( pExpr==0 ) return;
 76581         -  assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
        76777  +  assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
 76582  76778     z = pExpr->u.zToken;
 76583  76779     assert( z!=0 );
 76584  76780     assert( z[0]!=0 );
 76585  76781     if( z[1]==0 ){
 76586  76782       /* Wildcard of the form "?".  Assign the next variable number */
 76587  76783       assert( z[0]=='?' );
 76588  76784       pExpr->iColumn = (ynVar)(++pParse->nVar);
................................................................................
 76644  76840   /*
 76645  76841   ** Recursively delete an expression tree.
 76646  76842   */
 76647  76843   SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
 76648  76844     if( p==0 ) return;
 76649  76845     /* Sanity check: Assert that the IntValue is non-negative if it exists */
 76650  76846     assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
 76651         -  if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
        76847  +  if( !ExprHasProperty(p, EP_TokenOnly) ){
        76848  +    /* The Expr.x union is never used at the same time as Expr.pRight */
        76849  +    assert( p->x.pList==0 || p->pRight==0 );
 76652  76850       sqlite3ExprDelete(db, p->pLeft);
 76653  76851       sqlite3ExprDelete(db, p->pRight);
 76654         -    if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
 76655         -      sqlite3DbFree(db, p->u.zToken);
 76656         -    }
        76852  +    if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
 76657  76853       if( ExprHasProperty(p, EP_xIsSelect) ){
 76658  76854         sqlite3SelectDelete(db, p->x.pSelect);
 76659  76855       }else{
 76660  76856         sqlite3ExprListDelete(db, p->x.pList);
 76661  76857       }
 76662  76858     }
 76663  76859     if( !ExprHasProperty(p, EP_Static) ){
................................................................................
 76709  76905   ** to reduce a pristine expression tree from the parser.  The implementation
 76710  76906   ** of dupedExprStructSize() contain multiple assert() statements that attempt
 76711  76907   ** to enforce this constraint.
 76712  76908   */
 76713  76909   static int dupedExprStructSize(Expr *p, int flags){
 76714  76910     int nSize;
 76715  76911     assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
        76912  +  assert( EXPR_FULLSIZE<=0xfff );
        76913  +  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
 76716  76914     if( 0==(flags&EXPRDUP_REDUCE) ){
 76717  76915       nSize = EXPR_FULLSIZE;
 76718  76916     }else{
 76719         -    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
        76917  +    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
 76720  76918       assert( !ExprHasProperty(p, EP_FromJoin) ); 
 76721         -    assert( (p->flags2 & EP2_MallocedToken)==0 );
 76722         -    assert( (p->flags2 & EP2_Irreducible)==0 );
 76723         -    if( p->pLeft || p->pRight || p->x.pList ){
        76919  +    assert( !ExprHasProperty(p, EP_MemToken) );
        76920  +    assert( !ExprHasProperty(p, EP_NoReduce) );
        76921  +    if( p->pLeft || p->x.pList ){
 76724  76922         nSize = EXPR_REDUCEDSIZE | EP_Reduced;
 76725  76923       }else{
        76924  +      assert( p->pRight==0 );
 76726  76925         nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
 76727  76926       }
 76728  76927     }
 76729  76928     return nSize;
 76730  76929   }
 76731  76930   
 76732  76931   /*
................................................................................
 76812  77011         }else{
 76813  77012           int nSize = exprStructSize(p);
 76814  77013           memcpy(zAlloc, p, nSize);
 76815  77014           memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
 76816  77015         }
 76817  77016   
 76818  77017         /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
 76819         -      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
        77018  +      pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
 76820  77019         pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
 76821  77020         pNew->flags |= staticFlag;
 76822  77021   
 76823  77022         /* Copy the p->u.zToken string, if any. */
 76824  77023         if( nToken ){
 76825  77024           char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
 76826  77025           memcpy(zToken, p->u.zToken, nToken);
................................................................................
 76832  77031             pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
 76833  77032           }else{
 76834  77033             pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
 76835  77034           }
 76836  77035         }
 76837  77036   
 76838  77037         /* Fill in pNew->pLeft and pNew->pRight. */
 76839         -      if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
        77038  +      if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
 76840  77039           zAlloc += dupedExprNodeSize(p, flags);
 76841  77040           if( ExprHasProperty(pNew, EP_Reduced) ){
 76842  77041             pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
 76843  77042             pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
 76844  77043           }
 76845  77044           if( pzBuffer ){
 76846  77045             *pzBuffer = zAlloc;
 76847  77046           }
 76848  77047         }else{
 76849         -        pNew->flags2 = 0;
 76850         -        if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
        77048  +        if( !ExprHasProperty(p, EP_TokenOnly) ){
 76851  77049             pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
 76852  77050             pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
 76853  77051           }
 76854  77052         }
 76855  77053   
 76856  77054       }
 76857  77055     }
................................................................................
 77153  77351   **
 77154  77352   */
 77155  77353   static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
 77156  77354   
 77157  77355     /* If pWalker->u.i is 3 then any term of the expression that comes from
 77158  77356     ** the ON or USING clauses of a join disqualifies the expression
 77159  77357     ** from being considered constant. */
 77160         -  if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
        77358  +  if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
 77161  77359       pWalker->u.i = 0;
 77162  77360       return WRC_Abort;
 77163  77361     }
 77164  77362   
 77165  77363     switch( pExpr->op ){
 77166  77364       /* Consider functions to be constant if all their arguments are constant
 77167  77365       ** and pWalker->u.i==2 */
................................................................................
 77584  77782       eType = IN_INDEX_EPH;
 77585  77783       if( prNotFound ){
 77586  77784         *prNotFound = rMayHaveNull = ++pParse->nMem;
 77587  77785         sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
 77588  77786       }else{
 77589  77787         testcase( pParse->nQueryLoop>0 );
 77590  77788         pParse->nQueryLoop = 0;
 77591         -      if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
        77789  +      if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
 77592  77790           eType = IN_INDEX_ROWID;
 77593  77791         }
 77594  77792       }
 77595  77793       sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
 77596  77794       pParse->nQueryLoop = savedNQueryLoop;
 77597  77795     }else{
 77598  77796       pX->iTable = iTab;
................................................................................
 77653  77851     **    *  The right-hand side is a correlated subquery
 77654  77852     **    *  The right-hand side is an expression list containing variables
 77655  77853     **    *  We are inside a trigger
 77656  77854     **
 77657  77855     ** If all of the above are false, then we can run this code just once
 77658  77856     ** save the results, and reuse the same result on subsequent invocations.
 77659  77857     */
 77660         -  if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
        77858  +  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
 77661  77859       testAddr = sqlite3CodeOnce(pParse);
 77662  77860     }
 77663  77861   
 77664  77862   #ifndef SQLITE_OMIT_EXPLAIN
 77665  77863     if( pParse->explain==2 ){
 77666  77864       char *zMsg = sqlite3MPrintf(
 77667  77865           pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
................................................................................
 77822  78020         pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
 77823  78021                                     &sqlite3IntTokens[1]);
 77824  78022         pSel->iLimit = 0;
 77825  78023         if( sqlite3Select(pParse, pSel, &dest) ){
 77826  78024           return 0;
 77827  78025         }
 77828  78026         rReg = dest.iSDParm;
 77829         -      ExprSetIrreducible(pExpr);
        78027  +      ExprSetVVAProperty(pExpr, EP_NoReduce);
 77830  78028         break;
 77831  78029       }
 77832  78030     }
 77833  78031   
 77834  78032     if( testAddr>=0 ){
 77835  78033       sqlite3VdbeJumpHere(v, testAddr);
 77836  78034     }
................................................................................
 78293  78491     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
 78294  78492       int r = p->iReg;
 78295  78493       if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
 78296  78494     }
 78297  78495     return 0;
 78298  78496   }
 78299  78497   #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
        78498  +
        78499  +/*
        78500  +** Convert an expression node to a TK_REGISTER
        78501  +*/
        78502  +static void exprToRegister(Expr *p, int iReg){
        78503  +  p->op2 = p->op;
        78504  +  p->op = TK_REGISTER;
        78505  +  p->iTable = iReg;
        78506  +  ExprClearProperty(p, EP_Skip);
        78507  +}
 78300  78508   
 78301  78509   /*
 78302  78510   ** Generate code into the current Vdbe to evaluate the given
 78303  78511   ** expression.  Attempt to store the results in register "target".
 78304  78512   ** Return the register where results are stored.
 78305  78513   **
 78306  78514   ** With this routine, there is no guarantee that results will
................................................................................
 78419  78627       }
 78420  78628   #ifndef SQLITE_OMIT_CAST
 78421  78629       case TK_CAST: {
 78422  78630         /* Expressions of the form:   CAST(pLeft AS token) */
 78423  78631         int aff, to_op;
 78424  78632         inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
 78425  78633         assert( !ExprHasProperty(pExpr, EP_IntValue) );
 78426         -      aff = sqlite3AffinityType(pExpr->u.zToken);
        78634  +      aff = sqlite3AffinityType(pExpr->u.zToken, 0);
 78427  78635         to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
 78428  78636         assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
 78429  78637         assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
 78430  78638         assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
 78431  78639         assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
 78432  78640         assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
 78433  78641         testcase( to_op==OP_ToText );
................................................................................
 78593  78801         int i;                 /* Loop counter */
 78594  78802         u8 enc = ENC(db);      /* The text encoding used by this database */
 78595  78803         CollSeq *pColl = 0;    /* A collating sequence */
 78596  78804   
 78597  78805         assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
 78598  78806         testcase( op==TK_CONST_FUNC );
 78599  78807         testcase( op==TK_FUNCTION );
 78600         -      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
        78808  +      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
 78601  78809           pFarg = 0;
 78602  78810         }else{
 78603  78811           pFarg = pExpr->x.pList;
 78604  78812         }
 78605  78813         nFarg = pFarg ? pFarg->nExpr : 0;
 78606  78814         assert( !ExprHasProperty(pExpr, EP_IntValue) );
 78607  78815         zId = pExpr->u.zToken;
................................................................................
 78627  78835             sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
 78628  78836             sqlite3ExprCachePop(pParse, 1);
 78629  78837           }
 78630  78838           sqlite3VdbeResolveLabel(v, endCoalesce);
 78631  78839           break;
 78632  78840         }
 78633  78841   
        78842  +      /* The UNLIKELY() function is a no-op.  The result is the value
        78843  +      ** of the first argument.
        78844  +      */
        78845  +      if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
        78846  +        assert( nFarg>=1 );
        78847  +        sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
        78848  +        break;
        78849  +      }
 78634  78850   
 78635  78851         if( pFarg ){
 78636  78852           r1 = sqlite3GetTempRange(pParse, nFarg);
 78637  78853   
 78638  78854           /* For length() and typeof() functions with a column argument,
 78639  78855           ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
 78640  78856           ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
................................................................................
 78824  79040       **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
 78825  79041       **
 78826  79042       ** Form A is can be transformed into the equivalent form B as follows:
 78827  79043       **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
 78828  79044       **        WHEN x=eN THEN rN ELSE y END
 78829  79045       **
 78830  79046       ** X (if it exists) is in pExpr->pLeft.
 78831         -    ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
 78832         -    ** ELSE clause and no other term matches, then the result of the
 78833         -    ** exprssion is NULL.
        79047  +    ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
        79048  +    ** odd.  The Y is also optional.  If the number of elements in x.pList
        79049  +    ** is even, then Y is omitted and the "otherwise" result is NULL.
 78834  79050       ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
 78835  79051       **
 78836  79052       ** The result of the expression is the Ri for the first matching Ei,
 78837  79053       ** or if there is no matching Ei, the ELSE term Y, or if there is
 78838  79054       ** no ELSE term, NULL.
 78839  79055       */
 78840  79056       default: assert( op==TK_CASE ); {
................................................................................
 78847  79063         Expr opCompare;                   /* The X==Ei expression */
 78848  79064         Expr cacheX;                      /* Cached expression X */
 78849  79065         Expr *pX;                         /* The X expression */
 78850  79066         Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
 78851  79067         VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
 78852  79068   
 78853  79069         assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
 78854         -      assert((pExpr->x.pList->nExpr % 2) == 0);
 78855  79070         assert(pExpr->x.pList->nExpr > 0);
 78856  79071         pEList = pExpr->x.pList;
 78857  79072         aListelem = pEList->a;
 78858  79073         nExpr = pEList->nExpr;
 78859  79074         endLabel = sqlite3VdbeMakeLabel(v);
 78860  79075         if( (pX = pExpr->pLeft)!=0 ){
 78861  79076           cacheX = *pX;
 78862  79077           testcase( pX->op==TK_COLUMN );
 78863  79078           testcase( pX->op==TK_REGISTER );
 78864         -        cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
        79079  +        exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
 78865  79080           testcase( regFree1==0 );
 78866         -        cacheX.op = TK_REGISTER;
 78867  79081           opCompare.op = TK_EQ;
 78868  79082           opCompare.pLeft = &cacheX;
 78869  79083           pTest = &opCompare;
 78870  79084           /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
 78871  79085           ** The value in regFree1 might get SCopy-ed into the file result.
 78872  79086           ** So make sure that the regFree1 register is not reused for other
 78873  79087           ** purposes and possibly overwritten.  */
 78874  79088           regFree1 = 0;
 78875  79089         }
 78876         -      for(i=0; i<nExpr; i=i+2){
        79090  +      for(i=0; i<nExpr-1; i=i+2){
 78877  79091           sqlite3ExprCachePush(pParse);
 78878  79092           if( pX ){
 78879  79093             assert( pTest!=0 );
 78880  79094             opCompare.pRight = aListelem[i].pExpr;
 78881  79095           }else{
 78882  79096             pTest = aListelem[i].pExpr;
 78883  79097           }
................................................................................
 78887  79101           testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
 78888  79102           testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
 78889  79103           sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
 78890  79104           sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
 78891  79105           sqlite3ExprCachePop(pParse, 1);
 78892  79106           sqlite3VdbeResolveLabel(v, nextCase);
 78893  79107         }
 78894         -      if( pExpr->pRight ){
        79108  +      if( (nExpr&1)!=0 ){
 78895  79109           sqlite3ExprCachePush(pParse);
 78896         -        sqlite3ExprCode(pParse, pExpr->pRight, target);
        79110  +        sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
 78897  79111           sqlite3ExprCachePop(pParse, 1);
 78898  79112         }else{
 78899  79113           sqlite3VdbeAddOp2(v, OP_Null, 0, target);
 78900  79114         }
 78901  79115         assert( db->mallocFailed || pParse->nErr>0 
 78902  79116              || pParse->iCacheLevel==iCacheLevel );
 78903  79117         sqlite3VdbeResolveLabel(v, endLabel);
................................................................................
 79001  79215     ** no way for a TK_REGISTER to exist here.  But it seems prudent to
 79002  79216     ** keep the ALWAYS() in case the conditions above change with future
 79003  79217     ** modifications or enhancements. */
 79004  79218     if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
 79005  79219       int iMem;
 79006  79220       iMem = ++pParse->nMem;
 79007  79221       sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
 79008         -    pExpr->iTable = iMem;
 79009         -    pExpr->op2 = pExpr->op;
 79010         -    pExpr->op = TK_REGISTER;
        79222  +    exprToRegister(pExpr, iMem);
 79011  79223     }
 79012  79224     return inReg;
 79013  79225   }
 79014  79226   
 79015  79227   #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
 79016  79228   /*
 79017  79229   ** Generate a human-readable explanation of an expression tree.
................................................................................
 79082  79294         sqlite3ExplainExpr(pOut, pExpr->pLeft);
 79083  79295         break;
 79084  79296       }
 79085  79297   #ifndef SQLITE_OMIT_CAST
 79086  79298       case TK_CAST: {
 79087  79299         /* Expressions of the form:   CAST(pLeft AS token) */
 79088  79300         const char *zAff = "unk";
 79089         -      switch( sqlite3AffinityType(pExpr->u.zToken) ){
        79301  +      switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
 79090  79302           case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
 79091  79303           case SQLITE_AFF_NONE:    zAff = "NONE";     break;
 79092  79304           case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
 79093  79305           case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
 79094  79306           case SQLITE_AFF_REAL:    zAff = "REAL";     break;
 79095  79307         }
 79096  79308         sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
................................................................................
 79133  79345         break;
 79134  79346       }
 79135  79347   
 79136  79348       case TK_AGG_FUNCTION:
 79137  79349       case TK_CONST_FUNC:
 79138  79350       case TK_FUNCTION: {
 79139  79351         ExprList *pFarg;       /* List of function arguments */
 79140         -      if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
        79352  +      if( ExprHasProperty(pExpr, EP_TokenOnly) ){
 79141  79353           pFarg = 0;
 79142  79354         }else{
 79143  79355           pFarg = pExpr->x.pList;
 79144  79356         }
 79145  79357         if( op==TK_AGG_FUNCTION ){
 79146  79358           sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
 79147  79359                                pExpr->op2, pExpr->u.zToken);
................................................................................
 79382  79594     if( isAppropriateForFactoring(pExpr) ){
 79383  79595       int r1 = ++pParse->nMem;
 79384  79596       int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
 79385  79597       /* If r2!=r1, it means that register r1 is never used.  That is harmless
 79386  79598       ** but suboptimal, so we want to know about the situation to fix it.
 79387  79599       ** Hence the following assert: */
 79388  79600       assert( r2==r1 );
 79389         -    pExpr->op2 = pExpr->op;
 79390         -    pExpr->op = TK_REGISTER;
 79391         -    pExpr->iTable = r2;
        79601  +    exprToRegister(pExpr, r2);
 79392  79602       return WRC_Prune;
 79393  79603     }
 79394  79604     return WRC_Continue;
 79395  79605   }
 79396  79606   
 79397  79607   /*
 79398  79608   ** Preevaluate constant subexpressions within pExpr and store the
................................................................................
 79482  79692     exprAnd.pRight = &compRight;
 79483  79693     compLeft.op = TK_GE;
 79484  79694     compLeft.pLeft = &exprX;
 79485  79695     compLeft.pRight = pExpr->x.pList->a[0].pExpr;
 79486  79696     compRight.op = TK_LE;
 79487  79697     compRight.pLeft = &exprX;
 79488  79698     compRight.pRight = pExpr->x.pList->a[1].pExpr;
 79489         -  exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
 79490         -  exprX.op2 = exprX.op;
 79491         -  exprX.op = TK_REGISTER;
        79699  +  exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
 79492  79700     if( jumpIfTrue ){
 79493  79701       sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
 79494  79702     }else{
 79495  79703       sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
 79496  79704     }
 79497  79705     sqlite3ReleaseTempReg(pParse, regFree1);
 79498  79706   
................................................................................
 79799  80007   ** just might result in some slightly slower code.  But returning
 79800  80008   ** an incorrect 0 or 1 could lead to a malfunction.
 79801  80009   */
 79802  80010   SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
 79803  80011     if( pA==0||pB==0 ){
 79804  80012       return pB==pA ? 0 : 2;
 79805  80013     }
 79806         -  assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
 79807         -  assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
        80014  +  assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) );
        80015  +  assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) );
 79808  80016     if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
 79809  80017       return 2;
 79810  80018     }
 79811  80019     if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
 79812  80020     if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
 79813  80021       if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
 79814  80022         return 1;
................................................................................
 80014  80222         testcase( pExpr->op==TK_COLUMN );
 80015  80223         /* Check to see if the column is in one of the tables in the FROM
 80016  80224         ** clause of the aggregate query */
 80017  80225         if( ALWAYS(pSrcList!=0) ){
 80018  80226           struct SrcList_item *pItem = pSrcList->a;
 80019  80227           for(i=0; i<pSrcList->nSrc; i++, pItem++){
 80020  80228             struct AggInfo_col *pCol;
 80021         -          assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
        80229  +          assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 80022  80230             if( pExpr->iTable==pItem->iCursor ){
 80023  80231               /* If we reach this point, it means that pExpr refers to a table
 80024  80232               ** that is in the FROM clause of the aggregate query.  
 80025  80233               **
 80026  80234               ** Make an entry for the column in pAggInfo->aCol[] if there
 80027  80235               ** is not an entry there already.
 80028  80236               */
................................................................................
 80063  80271                 }
 80064  80272               }
 80065  80273               /* There is now an entry for pExpr in pAggInfo->aCol[] (either
 80066  80274               ** because it was there before or because we just created it).
 80067  80275               ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
 80068  80276               ** pAggInfo->aCol[] entry.
 80069  80277               */
 80070         -            ExprSetIrreducible(pExpr);
        80278  +            ExprSetVVAProperty(pExpr, EP_NoReduce);
 80071  80279               pExpr->pAggInfo = pAggInfo;
 80072  80280               pExpr->op = TK_AGG_COLUMN;
 80073  80281               pExpr->iAgg = (i16)k;
 80074  80282               break;
 80075  80283             } /* endif pExpr->iTable==pItem->iCursor */
 80076  80284           } /* end loop over pSrcList */
 80077  80285         }
................................................................................
 80109  80317               }else{
 80110  80318                 pItem->iDistinct = -1;
 80111  80319               }
 80112  80320             }
 80113  80321           }
 80114  80322           /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
 80115  80323           */
 80116         -        assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
 80117         -        ExprSetIrreducible(pExpr);
        80324  +        assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
        80325  +        ExprSetVVAProperty(pExpr, EP_NoReduce);
 80118  80326           pExpr->iAgg = (i16)i;
 80119  80327           pExpr->pAggInfo = pAggInfo;
 80120  80328           return WRC_Prune;
 80121  80329         }else{
 80122  80330           return WRC_Continue;
 80123  80331         }
 80124  80332       }
................................................................................
 81647  81855       if( p->nSample<p->mxSample 
 81648  81856        || sampleIsBetter(p, &p->current, &p->a[p->iMin]) 
 81649  81857       ){
 81650  81858         sampleInsert(p, &p->current, 0);
 81651  81859       }
 81652  81860     }
 81653  81861   #endif
        81862  +
        81863  +#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
        81864  +  UNUSED_PARAMETER( p );
        81865  +  UNUSED_PARAMETER( iChng );
        81866  +#endif
 81654  81867   }
 81655  81868   
 81656  81869   /*
 81657  81870   ** Implementation of the stat_push SQL function:  stat_push(P,R,C)
 81658  81871   ** Arguments:
 81659  81872   **
 81660  81873   **    P     Pointer to the Stat4Accum object created by stat_init()
................................................................................
 81672  81885   ){
 81673  81886     int i;
 81674  81887   
 81675  81888     /* The three function arguments */
 81676  81889     Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
 81677  81890     int iChng = sqlite3_value_int(argv[1]);
 81678  81891   
        81892  +  UNUSED_PARAMETER( argc );
        81893  +  UNUSED_PARAMETER( context );
 81679  81894     assert( p->nCol>1 );        /* Includes rowid field */
 81680  81895     assert( iChng<p->nCol );
 81681  81896   
 81682  81897     if( p->nRow==0 ){
 81683  81898       /* This is the first call to this function. Do initialization. */
 81684  81899       for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
 81685  81900     }else{
................................................................................
 81801  82016   
 81802  82017       char *zRet = sqlite3MallocZero(p->nCol * 25);
 81803  82018       if( zRet==0 ){
 81804  82019         sqlite3_result_error_nomem(context);
 81805  82020         return;
 81806  82021       }
 81807  82022   
 81808         -    sqlite3_snprintf(24, zRet, "%lld", p->nRow);
        82023  +    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
 81809  82024       z = zRet + sqlite3Strlen30(zRet);
 81810  82025       for(i=0; i<(p->nCol-1); i++){
 81811         -      i64 nDistinct = p->current.anDLt[i] + 1;
 81812         -      i64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
 81813         -      sqlite3_snprintf(24, z, " %lld", iVal);
        82026  +      u64 nDistinct = p->current.anDLt[i] + 1;
        82027  +      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
        82028  +      sqlite3_snprintf(24, z, " %llu", iVal);
 81814  82029         z += sqlite3Strlen30(z);
 81815  82030         assert( p->current.anEq[i] );
 81816  82031       }
 81817  82032       assert( z[0]=='\0' && z>zRet );
 81818  82033   
 81819  82034       sqlite3_result_text(context, zRet, -1, sqlite3_free);
 81820  82035     }
................................................................................
 81847  82062         char *zRet = sqlite3MallocZero(p->nCol * 25);
 81848  82063         if( zRet==0 ){
 81849  82064           sqlite3_result_error_nomem(context);
 81850  82065         }else{
 81851  82066           int i;
 81852  82067           char *z = zRet;
 81853  82068           for(i=0; i<p->nCol; i++){
 81854         -          sqlite3_snprintf(24, z, "%lld ", aCnt[i]);
        82069  +          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
 81855  82070             z += sqlite3Strlen30(z);
 81856  82071           }
 81857  82072           assert( z[0]=='\0' && z>zRet );
 81858  82073           z[-1] = '\0';
 81859  82074           sqlite3_result_text(context, zRet, -1, sqlite3_free);
 81860  82075         }
 81861  82076       }
 81862  82077     }
 81863  82078   #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
        82079  +#ifndef SQLITE_DEBUG
        82080  +  UNUSED_PARAMETER( argc );
        82081  +#endif
 81864  82082   }
 81865  82083   static const FuncDef statGetFuncdef = {
 81866  82084     1+IsStat34,      /* nArg */
 81867  82085     SQLITE_UTF8,     /* funcFlags */
 81868  82086     0,               /* pUserData */
 81869  82087     0,               /* pNext */
 81870  82088     statGet,         /* xFunc */
................................................................................
 81875  82093     0                /* pDestructor */
 81876  82094   };
 81877  82095   
 81878  82096   static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
 81879  82097     assert( regOut!=regStat4 && regOut!=regStat4+1 );
 81880  82098   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 81881  82099     sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
 81882         -#else
        82100  +#elif SQLITE_DEBUG
 81883  82101     assert( iParam==STAT_GET_STAT1 );
        82102  +#else
        82103  +  UNUSED_PARAMETER( iParam );
 81884  82104   #endif
 81885  82105     sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
 81886  82106     sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
 81887  82107     sqlite3VdbeChangeP5(v, 1 + IsStat34);
 81888  82108   }
 81889  82109   
 81890  82110   /*
................................................................................
 82308  82528   
 82309  82529   /*
 82310  82530   ** The first argument points to a nul-terminated string containing a
 82311  82531   ** list of space separated integers. Read the first nOut of these into
 82312  82532   ** the array aOut[].
 82313  82533   */
 82314  82534   static void decodeIntArray(
 82315         -  char *zIntArray, 
 82316         -  int nOut, 
 82317         -  tRowcnt *aOut, 
 82318         -  int *pbUnordered
        82535  +  char *zIntArray,       /* String containing int array to decode */
        82536  +  int nOut,              /* Number of slots in aOut[] */
        82537  +  tRowcnt *aOut,         /* Store integers here */
        82538  +  Index *pIndex          /* Handle extra flags for this index, if not NULL */
 82319  82539   ){
 82320  82540     char *z = zIntArray;
 82321  82541     int c;
 82322  82542     int i;
 82323  82543     tRowcnt v;
 82324  82544   
 82325         -  assert( pbUnordered==0 || *pbUnordered==0 );
 82326         -
 82327  82545   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
 82328  82546     if( z==0 ) z = "";
 82329  82547   #else
 82330  82548     if( NEVER(z==0) ) z = "";
 82331  82549   #endif
 82332  82550     for(i=0; *z && i<nOut; i++){
 82333  82551       v = 0;
................................................................................
 82334  82552       while( (c=z[0])>='0' && c<='9' ){
 82335  82553         v = v*10 + c - '0';
 82336  82554         z++;
 82337  82555       }
 82338  82556       aOut[i] = v;
 82339  82557       if( *z==' ' ) z++;
 82340  82558     }
 82341         -  if( pbUnordered && strcmp(z, "unordered")==0 ){
 82342         -    *pbUnordered = 1;
        82559  +#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
        82560  +  assert( pIndex!=0 );
        82561  +#else
        82562  +  if( pIndex )
        82563  +#endif
        82564  +  {
        82565  +    if( strcmp(z, "unordered")==0 ){
        82566  +      pIndex->bUnordered = 1;
        82567  +    }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
        82568  +      int v32 = 0;
        82569  +      sqlite3GetInt32(z+3, &v32);
        82570  +      pIndex->szIdxRow = sqlite3LogEst(v32);
        82571  +    }
 82343  82572     }
 82344  82573   }
 82345  82574   
 82346  82575   /*
 82347  82576   ** This callback is invoked once for each index when reading the
 82348  82577   ** sqlite_stat1 table.  
 82349  82578   **
................................................................................
 82374  82603       pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
 82375  82604     }else{
 82376  82605       pIndex = 0;
 82377  82606     }
 82378  82607     z = argv[2];
 82379  82608   
 82380  82609     if( pIndex ){
 82381         -    int bUnordered = 0;
 82382         -    decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst,&bUnordered);
        82610  +    decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex);
 82383  82611       if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
 82384         -    pIndex->bUnordered = bUnordered;
 82385  82612     }else{
 82386         -    decodeIntArray((char*)z, 1, &pTable->nRowEst, 0);
        82613  +    Index fakeIdx;
        82614  +    fakeIdx.szIdxRow = pTable->szTabRow;
        82615  +    decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx);
        82616  +    pTable->szTabRow = fakeIdx.szIdxRow;
 82387  82617     }
 82388  82618   
 82389  82619     return 0;
 82390  82620   }
 82391  82621   
 82392  82622   /*
 82393  82623   ** If the Index.aSample variable is not NULL, delete the aSample[] array
................................................................................
 83102  83332     codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
 83103  83333   }
 83104  83334   #endif /* SQLITE_OMIT_ATTACH */
 83105  83335   
 83106  83336   /*
 83107  83337   ** Initialize a DbFixer structure.  This routine must be called prior
 83108  83338   ** to passing the structure to one of the sqliteFixAAAA() routines below.
 83109         -**
 83110         -** The return value indicates whether or not fixation is required.  TRUE
 83111         -** means we do need to fix the database references, FALSE means we do not.
 83112  83339   */
 83113         -SQLITE_PRIVATE int sqlite3FixInit(
        83340  +SQLITE_PRIVATE void sqlite3FixInit(
 83114  83341     DbFixer *pFix,      /* The fixer to be initialized */
 83115  83342     Parse *pParse,      /* Error messages will be written here */
 83116  83343     int iDb,            /* This is the database that must be used */
 83117  83344     const char *zType,  /* "view", "trigger", or "index" */
 83118  83345     const Token *pName  /* Name of the view, trigger, or index */
 83119  83346   ){
 83120  83347     sqlite3 *db;
 83121  83348   
 83122         -  if( NEVER(iDb<0) || iDb==1 ) return 0;
 83123  83349     db = pParse->db;
 83124  83350     assert( db->nDb>iDb );
 83125  83351     pFix->pParse = pParse;
 83126  83352     pFix->zDb = db->aDb[iDb].zName;
 83127  83353     pFix->pSchema = db->aDb[iDb].pSchema;
 83128  83354     pFix->zType = zType;
 83129  83355     pFix->pName = pName;
 83130         -  return 1;
        83356  +  pFix->bVarOnly = (iDb==1);
 83131  83357   }
 83132  83358   
 83133  83359   /*
 83134  83360   ** The following set of routines walk through the parse tree and assign
 83135  83361   ** a specific database to all table references where the database name
 83136  83362   ** was left unspecified in the original SQL statement.  The pFix structure
 83137  83363   ** must have been initialized by a prior call to sqlite3FixInit().
................................................................................
 83151  83377     int i;
 83152  83378     const char *zDb;
 83153  83379     struct SrcList_item *pItem;
 83154  83380   
 83155  83381     if( NEVER(pList==0) ) return 0;
 83156  83382     zDb = pFix->zDb;
 83157  83383     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
 83158         -    if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
 83159         -      sqlite3ErrorMsg(pFix->pParse,
 83160         -         "%s %T cannot reference objects in database %s",
 83161         -         pFix->zType, pFix->pName, pItem->zDatabase);
 83162         -      return 1;
        83384  +    if( pFix->bVarOnly==0 ){
        83385  +      if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
        83386  +        sqlite3ErrorMsg(pFix->pParse,
        83387  +            "%s %T cannot reference objects in database %s",
        83388  +            pFix->zType, pFix->pName, pItem->zDatabase);
        83389  +        return 1;
        83390  +      }
        83391  +      sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
        83392  +      pItem->zDatabase = 0;
        83393  +      pItem->pSchema = pFix->pSchema;
 83163  83394       }
 83164         -    sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
 83165         -    pItem->zDatabase = 0;
 83166         -    pItem->pSchema = pFix->pSchema;
 83167  83395   #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
 83168  83396       if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
 83169  83397       if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
 83170  83398   #endif
 83171  83399     }
 83172  83400     return 0;
 83173  83401   }
................................................................................
 83181  83409         return 1;
 83182  83410       }
 83183  83411       if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
 83184  83412         return 1;
 83185  83413       }
 83186  83414       if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
 83187  83415         return 1;
        83416  +    }
        83417  +    if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
        83418  +      return 1;
 83188  83419       }
 83189  83420       if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
 83190  83421         return 1;
        83422  +    }
        83423  +    if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
        83424  +      return 1;
        83425  +    }
        83426  +    if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
        83427  +      return 1;
        83428  +    }
        83429  +    if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
        83430  +      return 1;
 83191  83431       }
 83192  83432       pSelect = pSelect->pPrior;
 83193  83433     }
 83194  83434     return 0;
 83195  83435   }
 83196  83436   SQLITE_PRIVATE int sqlite3FixExpr(
 83197  83437     DbFixer *pFix,     /* Context of the fixation */
 83198  83438     Expr *pExpr        /* The expression to be fixed to one database */
 83199  83439   ){
 83200  83440     while( pExpr ){
 83201         -    if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
        83441  +    if( pExpr->op==TK_VARIABLE ){
        83442  +      if( pFix->pParse->db->init.busy ){
        83443  +        pExpr->op = TK_NULL;
        83444  +      }else{
        83445  +        sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
        83446  +        return 1;
        83447  +      }
        83448  +    }
        83449  +    if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
 83202  83450       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
 83203  83451         if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
 83204  83452       }else{
 83205  83453         if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
 83206  83454       }
 83207  83455       if( sqlite3FixExpr(pFix, pExpr->pRight) ){
 83208  83456         return 1;
................................................................................
 84377  84625       pParse->nErr++;
 84378  84626       goto begin_table_error;
 84379  84627     }
 84380  84628     pTable->zName = zName;
 84381  84629     pTable->iPKey = -1;
 84382  84630     pTable->pSchema = db->aDb[iDb].pSchema;
 84383  84631     pTable->nRef = 1;
 84384         -  pTable->nRowEst = 1000000;
        84632  +  pTable->nRowEst = 1048576;
 84385  84633     assert( pParse->pNewTable==0 );
 84386  84634     pParse->pNewTable = pTable;
 84387  84635   
 84388  84636     /* If this is the magic sqlite_sequence table used by autoincrement,
 84389  84637     ** then record a pointer to this table in the main database structure
 84390  84638     ** so that INSERT can find the table easily.
 84391  84639     */
................................................................................
 84524  84772     pCol->zName = z;
 84525  84773    
 84526  84774     /* If there is no type specified, columns have the default affinity
 84527  84775     ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
 84528  84776     ** be called next to set pCol->affinity correctly.
 84529  84777     */
 84530  84778     pCol->affinity = SQLITE_AFF_NONE;
        84779  +  pCol->szEst = 1;
 84531  84780     p->nCol++;
 84532  84781   }
 84533  84782   
 84534  84783   /*
 84535  84784   ** This routine is called by the parser while in the middle of
 84536  84785   ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
 84537  84786   ** been seen on a column.  This routine sets the notNull flag on
................................................................................
 84565  84814   ** 'REAL'        | SQLITE_AFF_REAL
 84566  84815   ** 'FLOA'        | SQLITE_AFF_REAL
 84567  84816   ** 'DOUB'        | SQLITE_AFF_REAL
 84568  84817   **
 84569  84818   ** If none of the substrings in the above table are found,
 84570  84819   ** SQLITE_AFF_NUMERIC is returned.
 84571  84820   */
 84572         -SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
        84821  +SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
 84573  84822     u32 h = 0;
 84574  84823     char aff = SQLITE_AFF_NUMERIC;
        84824  +  const char *zChar = 0;
 84575  84825   
 84576         -  if( zIn ) while( zIn[0] ){
        84826  +  if( zIn==0 ) return aff;
        84827  +  while( zIn[0] ){
 84577  84828       h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
 84578  84829       zIn++;
 84579  84830       if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
 84580         -      aff = SQLITE_AFF_TEXT; 
        84831  +      aff = SQLITE_AFF_TEXT;
        84832  +      zChar = zIn;
 84581  84833       }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
 84582  84834         aff = SQLITE_AFF_TEXT;
 84583  84835       }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
 84584  84836         aff = SQLITE_AFF_TEXT;
 84585  84837       }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
 84586  84838           && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
 84587  84839         aff = SQLITE_AFF_NONE;
        84840  +      if( zIn[0]=='(' ) zChar = zIn;
 84588  84841   #ifndef SQLITE_OMIT_FLOATING_POINT
 84589  84842       }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
 84590  84843           && aff==SQLITE_AFF_NUMERIC ){
 84591  84844         aff = SQLITE_AFF_REAL;
 84592  84845       }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
 84593  84846           && aff==SQLITE_AFF_NUMERIC ){
 84594  84847         aff = SQLITE_AFF_REAL;
................................................................................
 84598  84851   #endif
 84599  84852       }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
 84600  84853         aff = SQLITE_AFF_INTEGER;
 84601  84854         break;
 84602  84855       }
 84603  84856     }
 84604  84857   
        84858  +  /* If pszEst is not NULL, store an estimate of the field size.  The
        84859  +  ** estimate is scaled so that the size of an integer is 1.  */
        84860  +  if( pszEst ){
        84861  +    *pszEst = 1;   /* default size is approx 4 bytes */
        84862  +    if( aff<=SQLITE_AFF_NONE ){
        84863  +      if( zChar ){
        84864  +        while( zChar[0] ){
        84865  +          if( sqlite3Isdigit(zChar[0]) ){
        84866  +            int v = 0;
        84867  +            sqlite3GetInt32(zChar, &v);
        84868  +            v = v/4 + 1;
        84869  +            if( v>255 ) v = 255;
        84870  +            *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
        84871  +            break;
        84872  +          }
        84873  +          zChar++;
        84874  +        }
        84875  +      }else{
        84876  +        *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
        84877  +      }
        84878  +    }
        84879  +  }
 84605  84880     return aff;
 84606  84881   }
 84607  84882   
 84608  84883   /*
 84609  84884   ** This routine is called by the parser while in the middle of
 84610  84885   ** parsing a CREATE TABLE statement.  The pFirst token is the first
 84611  84886   ** token in the sequence of tokens that describe the type of the
................................................................................
 84619  84894     Column *pCol;
 84620  84895   
 84621  84896     p = pParse->pNewTable;
 84622  84897     if( p==0 || NEVER(p->nCol<1) ) return;
 84623  84898     pCol = &p->aCol[p->nCol-1];
 84624  84899     assert( pCol->zType==0 );
 84625  84900     pCol->zType = sqlite3NameFromToken(pParse->db, pType);
 84626         -  pCol->affinity = sqlite3AffinityType(pCol->zType);
        84901  +  pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
 84627  84902   }
 84628  84903   
 84629  84904   /*
 84630  84905   ** The expression is the default value for the most recently added column
 84631  84906   ** of the table currently under construction.
 84632  84907   **
 84633  84908   ** Default value expressions must be constant.  Raise an exception if this
................................................................................
 84967  85242       testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
 84968  85243       testcase( pCol->affinity==SQLITE_AFF_INTEGER );
 84969  85244       testcase( pCol->affinity==SQLITE_AFF_REAL );
 84970  85245       
 84971  85246       zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
 84972  85247       len = sqlite3Strlen30(zType);
 84973  85248       assert( pCol->affinity==SQLITE_AFF_NONE 
 84974         -            || pCol->affinity==sqlite3AffinityType(zType) );
        85249  +            || pCol->affinity==sqlite3AffinityType(zType, 0) );
 84975  85250       memcpy(&zStmt[k], zType, len);
 84976  85251       k += len;
 84977  85252       assert( k<=n );
 84978  85253     }
 84979  85254     sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
 84980  85255     return zStmt;
 84981  85256   }
        85257  +
        85258  +/*
        85259  +** Estimate the total row width for a table.
        85260  +*/
        85261  +static void estimateTableWidth(Table *pTab){
        85262  +  unsigned wTable = 0;
        85263  +  const Column *pTabCol;
        85264  +  int i;
        85265  +  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
        85266  +    wTable += pTabCol->szEst;
        85267  +  }
        85268  +  if( pTab->iPKey<0 ) wTable++;
        85269  +  pTab->szTabRow = sqlite3LogEst(wTable*4);
        85270  +}
        85271  +
        85272  +/*
        85273  +** Estimate the average size of a row for an index.
        85274  +*/
        85275  +static void estimateIndexWidth(Index *pIdx){
        85276  +  unsigned wIndex = 1;
        85277  +  int i;
        85278  +  const Column *aCol = pIdx->pTable->aCol;
        85279  +  for(i=0; i<pIdx->nColumn; i++){
        85280  +    assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]<pIdx->pTable->nCol );
        85281  +    wIndex += aCol[pIdx->aiColumn[i]].szEst;
        85282  +  }
        85283  +  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
        85284  +}
 84982  85285   
 84983  85286   /*
 84984  85287   ** This routine is called to report the final ")" that terminates
 84985  85288   ** a CREATE TABLE statement.
 84986  85289   **
 84987  85290   ** The table structure that other action routines have been building
 84988  85291   ** is added to the internal hash tables, assuming no errors have
................................................................................
 85002  85305   */
 85003  85306   SQLITE_PRIVATE void sqlite3EndTable(
 85004  85307     Parse *pParse,          /* Parse context */
 85005  85308     Token *pCons,           /* The ',' token after the last column defn. */
 85006  85309     Token *pEnd,            /* The final ')' token in the CREATE TABLE */
 85007  85310     Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
 85008  85311   ){
 85009         -  Table *p;
 85010         -  sqlite3 *db = pParse->db;
 85011         -  int iDb;
        85312  +  Table *p;                 /* The new table */
        85313  +  sqlite3 *db = pParse->db; /* The database connection */
        85314  +  int iDb;                  /* Database in which the table lives */
        85315  +  Index *pIdx;              /* An implied index of the table */
 85012  85316   
 85013  85317     if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
 85014  85318       return;
 85015  85319     }
 85016  85320     p = pParse->pNewTable;
 85017  85321     if( p==0 ) return;
 85018  85322   
................................................................................
 85023  85327   #ifndef SQLITE_OMIT_CHECK
 85024  85328     /* Resolve names in all CHECK constraint expressions.
 85025  85329     */
 85026  85330     if( p->pCheck ){
 85027  85331       sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
 85028  85332     }
 85029  85333   #endif /* !defined(SQLITE_OMIT_CHECK) */
        85334  +
        85335  +  /* Estimate the average row size for the table and for all implied indices */
        85336  +  estimateTableWidth(p);
        85337  +  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
        85338  +    estimateIndexWidth(pIdx);
        85339  +  }
 85030  85340   
 85031  85341     /* If the db->init.busy is 1 it means we are reading the SQL off the
 85032  85342     ** "sqlite_master" or "sqlite_temp_master" table on the disk.
 85033  85343     ** So do not write to the disk again.  Extract the root page number
 85034  85344     ** for the table from the db->init.newTnum field.  (The page number
 85035  85345     ** should have been put there by the sqliteOpenCb routine.)
 85036  85346     */
................................................................................
 85220  85530     p = pParse->pNewTable;
 85221  85531     if( p==0 || pParse->nErr ){
 85222  85532       sqlite3SelectDelete(db, pSelect);
 85223  85533       return;
 85224  85534     }
 85225  85535     sqlite3TwoPartName(pParse, pName1, pName2, &pName);
 85226  85536     iDb = sqlite3SchemaToIndex(db, p->pSchema);
 85227         -  if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
 85228         -    && sqlite3FixSelect(&sFix, pSelect)
 85229         -  ){
        85537  +  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
        85538  +  if( sqlite3FixSelect(&sFix, pSelect) ){
 85230  85539       sqlite3SelectDelete(db, pSelect);
 85231  85540       return;
 85232  85541     }
 85233  85542   
 85234  85543     /* Make a copy of the entire SELECT statement that defines the view.
 85235  85544     ** This will force all the Expr.token.z values to be dynamically
 85236  85545     ** allocated rather than point to the input string - which means that
................................................................................
 85983  86292     DbFixer sFix;        /* For assigning database names to pTable */
 85984  86293     int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
 85985  86294     sqlite3 *db = pParse->db;
 85986  86295     Db *pDb;             /* The specific table containing the indexed database */
 85987  86296     int iDb;             /* Index of the database that is being written */
 85988  86297     Token *pName = 0;    /* Unqualified name of the index to create */
 85989  86298     struct ExprList_item *pListItem; /* For looping over pList */
 85990         -  int nCol;
 85991         -  int nExtra = 0;
 85992         -  char *zExtra;
        86299  +  const Column *pTabCol;           /* A column in the table */
        86300  +  int nCol;                        /* Number of columns */
        86301  +  int nExtra = 0;                  /* Space allocated for zExtra[] */
        86302  +  char *zExtra;                    /* Extra space after the Index object */
 85993  86303   
 85994  86304     assert( pParse->nErr==0 );      /* Never called with prior errors */
 85995  86305     if( db->mallocFailed || IN_DECLARE_VTAB ){
 85996  86306       goto exit_create_index;
 85997  86307     }
 85998  86308     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
 85999  86309       goto exit_create_index;
................................................................................
 86022  86332         pTab = sqlite3SrcListLookup(pParse, pTblName);
 86023  86333         if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
 86024  86334           iDb = 1;
 86025  86335         }
 86026  86336       }
 86027  86337   #endif
 86028  86338   
 86029         -    if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
 86030         -        sqlite3FixSrcList(&sFix, pTblName)
 86031         -    ){
        86339  +    sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
        86340  +    if( sqlite3FixSrcList(&sFix, pTblName) ){
 86032  86341         /* Because the parser constructs pTblName from a single identifier,
 86033  86342         ** sqlite3FixSrcList can never fail. */
 86034  86343         assert(0);
 86035  86344       }
 86036  86345       pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
 86037  86346       assert( db->mallocFailed==0 || pTab==0 );
 86038  86347       if( pTab==0 ) goto exit_create_index;
................................................................................
 86213  86522     ** more than once within the same index.  Only the first instance of
 86214  86523     ** the column will ever be used by the optimizer.  Note that using the
 86215  86524     ** same column more than once cannot be an error because that would 
 86216  86525     ** break backwards compatibility - it needs to be a warning.
 86217  86526     */
 86218  86527     for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
 86219  86528       const char *zColName = pListItem->zName;
 86220         -    Column *pTabCol;
 86221  86529       int requestedSortOrder;
 86222  86530       char *zColl;                   /* Collation sequence name */
 86223  86531   
 86224  86532       for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
 86225  86533         if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
 86226  86534       }
 86227  86535       if( j>=pTab->nCol ){
................................................................................
 86250  86558       }
 86251  86559       pIndex->azColl[i] = zColl;
 86252  86560       requestedSortOrder = pListItem->sortOrder & sortOrderMask;
 86253  86561       pIndex->aSortOrder[i] = (u8)requestedSortOrder;
 86254  86562       if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
 86255  86563     }
 86256  86564     sqlite3DefaultRowEst(pIndex);
        86565  +  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
 86257  86566   
 86258  86567     if( pTab==pParse->pNewTable ){
 86259  86568       /* This routine has been called to create an automatic index as a
 86260  86569       ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
 86261  86570       ** a PRIMARY KEY or UNIQUE clause following the column definitions.
 86262  86571       ** i.e. one of:
 86263  86572       **
................................................................................
 88155  88464     ** It is easier just to erase the whole table. Prior to version 3.6.5,
 88156  88465     ** this optimization caused the row change count (the value returned by 
 88157  88466     ** API function sqlite3_count_changes) to be set incorrectly.  */
 88158  88467     if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
 88159  88468      && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
 88160  88469     ){
 88161  88470       assert( !isView );
        88471  +    sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
 88162  88472       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
 88163  88473                         pTab->zName, P4_STATIC);
 88164  88474       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
 88165  88475         assert( pIdx->pSchema==pTab->pSchema );
 88166  88476         sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
 88167  88477       }
 88168  88478     }else
................................................................................
 88897  89207         }
 88898  89208         sqlite3_result_text(context, z1, n, sqlite3_free);
 88899  89209       }
 88900  89210     }
 88901  89211   }
 88902  89212   
 88903  89213   /*
 88904         -** The COALESCE() and IFNULL() functions are implemented as VDBE code so
 88905         -** that unused argument values do not have to be computed.  However, we
 88906         -** still need some kind of function implementation for this routines in
 88907         -** the function table.  That function implementation will never be called
 88908         -** so it doesn't matter what the implementation is.  We might as well use
 88909         -** the "version()" function as a substitute.
        89214  +** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
        89215  +** as VDBE code so that unused argument values do not have to be computed.
        89216  +** However, we still need some kind of function implementation for this
        89217  +** routines in the function table.  The noopFunc macro provides this.
        89218  +** noopFunc will never be called so it doesn't matter what the implementation
        89219  +** is.  We might as well use the "version()" function as a substitute.
 88910  89220   */
 88911         -#define ifnullFunc versionFunc   /* Substitute function - never called */
        89221  +#define noopFunc versionFunc   /* Substitute function - never called */
 88912  89222   
 88913  89223   /*
 88914  89224   ** Implementation of random().  Return a random integer.  
 88915  89225   */
 88916  89226   static void randomFunc(
 88917  89227     sqlite3_context *context,
 88918  89228     int NotUsed,
................................................................................
 89023  89333   ** For LIKE and GLOB matching on EBCDIC machines, assume that every
 89024  89334   ** character is exactly one byte in size.  Also, all characters are
 89025  89335   ** able to participate in upper-case-to-lower-case mappings in EBCDIC
 89026  89336   ** whereas only characters less than 0x80 do in ASCII.
 89027  89337   */
 89028  89338   #if defined(SQLITE_EBCDIC)
 89029  89339   # define sqlite3Utf8Read(A)    (*((*A)++))
 89030         -# define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
        89340  +# define GlobUpperToLower(A)   A = sqlite3UpperToLower[A]
 89031  89341   #else
 89032         -# define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
        89342  +# define GlobUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
 89033  89343   #endif
 89034  89344   
 89035  89345   static const struct compareInfo globInfo = { '*', '?', '[', 0 };
 89036  89346   /* The correct SQL-92 behavior is for the LIKE operator to ignore
 89037  89347   ** case.  Thus  'a' LIKE 'A' would be true. */
 89038  89348   static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
 89039  89349   /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
................................................................................
 89104  89414           while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
 89105  89415             SQLITE_SKIP_UTF8(zString);
 89106  89416           }
 89107  89417           return *zString!=0;
 89108  89418         }
 89109  89419         while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
 89110  89420           if( noCase ){
 89111         -          GlogUpperToLower(c2);
 89112         -          GlogUpperToLower(c);
        89421  +          GlobUpperToLower(c2);
        89422  +          GlobUpperToLower(c);
 89113  89423             while( c2 != 0 && c2 != c ){
 89114  89424               c2 = sqlite3Utf8Read(&zString);
 89115         -            GlogUpperToLower(c2);
        89425  +            GlobUpperToLower(c2);
 89116  89426             }
 89117  89427           }else{
 89118  89428             while( c2 != 0 && c2 != c ){
 89119  89429               c2 = sqlite3Utf8Read(&zString);
 89120  89430             }
 89121  89431           }
 89122  89432           if( c2==0 ) return 0;
................................................................................
 89160  89470           return 0;
 89161  89471         }
 89162  89472       }else if( esc==c && !prevEscape ){
 89163  89473         prevEscape = 1;
 89164  89474       }else{
 89165  89475         c2 = sqlite3Utf8Read(&zString);
 89166  89476         if( noCase ){
 89167         -        GlogUpperToLower(c);
 89168         -        GlogUpperToLower(c2);
        89477  +        GlobUpperToLower(c);
        89478  +        GlobUpperToLower(c2);
 89169  89479         }
 89170  89480         if( c!=c2 ){
 89171  89481           return 0;
 89172  89482         }
 89173  89483         prevEscape = 0;
 89174  89484       }
 89175  89485     }
................................................................................
 90138  90448       FUNCTION(round,              1, 0, 0, roundFunc        ),
 90139  90449       FUNCTION(round,              2, 0, 0, roundFunc        ),
 90140  90450   #endif
 90141  90451       FUNCTION(upper,              1, 0, 0, upperFunc        ),
 90142  90452       FUNCTION(lower,              1, 0, 0, lowerFunc        ),
 90143  90453       FUNCTION(coalesce,           1, 0, 0, 0                ),
 90144  90454       FUNCTION(coalesce,           0, 0, 0, 0                ),
 90145         -    FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
        90455  +    FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
 90146  90456       FUNCTION(hex,                1, 0, 0, hexFunc          ),
 90147         -    FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
        90457  +    FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
        90458  +    FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
        90459  +    FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
 90148  90460       FUNCTION(random,             0, 0, 0, randomFunc       ),
 90149  90461       FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
 90150  90462       FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
 90151  90463       FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
 90152  90464       FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
 90153  90465       FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
 90154  90466   #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
................................................................................
 90858  91170         /* Search for a deferred foreign key constraint for which this table
 90859  91171         ** is the child table. If one cannot be found, return without 
 90860  91172         ** generating any VDBE code. If one can be found, then jump over
 90861  91173         ** the entire DELETE if there are no outstanding deferred constraints
 90862  91174         ** when this statement is run.  */
 90863  91175         FKey *p;
 90864  91176         for(p=pTab->pFKey; p; p=p->pNextFrom){
 90865         -        if( p->isDeferred ) break;
        91177  +        if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
 90866  91178         }
 90867  91179         if( !p ) return;
 90868  91180         iSkip = sqlite3VdbeMakeLabel(v);
 90869  91181         sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
 90870  91182       }
 90871  91183   
 90872  91184       pParse->disableTriggers = 1;
 90873  91185       sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
 90874  91186       pParse->disableTriggers = 0;
 90875  91187   
 90876  91188       /* If the DELETE has generated immediate foreign key constraint 
 90877  91189       ** violations, halt the VDBE and return an error at this point, before
 90878  91190       ** any modifications to the schema are made. This is because statement
 90879         -    ** transactions are not able to rollback schema changes.  */
 90880         -    sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
 90881         -    sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
 90882         -        OE_Abort, "foreign key constraint failed", P4_STATIC
 90883         -    );
        91191  +    ** transactions are not able to rollback schema changes.  
        91192  +    **
        91193  +    ** If the SQLITE_DeferFKs flag is set, then this is not required, as
        91194  +    ** the statement transaction will not be rolled back even if FK
        91195  +    ** constraints are violated.
        91196  +    */
        91197  +    if( (db->flags & SQLITE_DeferFKs)==0 ){
        91198  +      sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
        91199  +      sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
        91200  +          OE_Abort, "foreign key constraint failed", P4_STATIC
        91201  +      );
        91202  +    }
 90884  91203   
 90885  91204       if( iSkip ){
 90886  91205         sqlite3VdbeResolveLabel(v, iSkip);
 90887  91206       }
 90888  91207     }
 90889  91208   }
 90890  91209   
................................................................................
 93402  93721       pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
 93403  93722       sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
 93404  93723                         (char*)pKey, P4_KEYINFO_HANDOFF);
 93405  93724       VdbeComment((v, "%s", pSrcIdx->zName));
 93406  93725       pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
 93407  93726       sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
 93408  93727                         (char*)pKey, P4_KEYINFO_HANDOFF);
        93728  +    sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
 93409  93729       VdbeComment((v, "%s", pDestIdx->zName));
 93410  93730       addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
 93411  93731       sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
 93412  93732       sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
 93413  93733       sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
 93414  93734       sqlite3VdbeJumpHere(v, addr1);
 93415  93735     }
................................................................................
 94834  95154   **    May you find forgiveness for yourself and forgive others.
 94835  95155   **    May you share freely, never taking more than you give.
 94836  95156   **
 94837  95157   *************************************************************************
 94838  95158   ** This file contains code used to implement the PRAGMA command.
 94839  95159   */
 94840  95160   
        95161  +#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
        95162  +#  if defined(__APPLE__)
        95163  +#    define SQLITE_ENABLE_LOCKING_STYLE 1
        95164  +#  else
        95165  +#    define SQLITE_ENABLE_LOCKING_STYLE 0
        95166  +#  endif
        95167  +#endif
        95168  +
        95169  +/***************************************************************************
        95170  +** The next block of code, including the PragTyp_XXXX macro definitions and
        95171  +** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
        95172  +**
        95173  +** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
        95174  +** that script.  Then copy/paste the output in place of the following:
        95175  +*/
        95176  +#define PragTyp_HEADER_VALUE                   0
        95177  +#define PragTyp_AUTO_VACUUM                    1
        95178  +#define PragTyp_FLAG                           2
        95179  +#define PragTyp_BUSY_TIMEOUT                   3
        95180  +#define PragTyp_CACHE_SIZE                     4
        95181  +#define PragTyp_CASE_SENSITIVE_LIKE            5
        95182  +#define PragTyp_COLLATION_LIST                 6
        95183  +#define PragTyp_COMPILE_OPTIONS                7
        95184  +#define PragTyp_DATA_STORE_DIRECTORY           8
        95185  +#define PragTyp_DATABASE_LIST                  9
        95186  +#define PragTyp_DEFAULT_CACHE_SIZE            10
        95187  +#define PragTyp_ENCODING                      11
        95188  +#define PragTyp_FOREIGN_KEY_CHECK             12
        95189  +#define PragTyp_FOREIGN_KEY_LIST              13
        95190  +#define PragTyp_INCREMENTAL_VACUUM            14
        95191  +#define PragTyp_INDEX_INFO                    15
        95192  +#define PragTyp_INDEX_LIST                    16
        95193  +#define PragTyp_INTEGRITY_CHECK               17
        95194  +#define PragTyp_JOURNAL_MODE                  18
        95195  +#define PragTyp_JOURNAL_SIZE_LIMIT            19
        95196  +#define PragTyp_LOCK_PROXY_FILE               20
        95197  +#define PragTyp_LOCKING_MODE                  21
        95198  +#define PragTyp_PAGE_COUNT                    22
        95199  +#define PragTyp_MMAP_SIZE                     23
        95200  +#define PragTyp_PAGE_SIZE                     24
        95201  +#define PragTyp_SECURE_DELETE                 25
        95202  +#define PragTyp_SHRINK_MEMORY                 26
        95203  +#define PragTyp_SOFT_HEAP_LIMIT               27
        95204  +#define PragTyp_STATS                         28
        95205  +#define PragTyp_SYNCHRONOUS                   29
        95206  +#define PragTyp_TABLE_INFO                    30
        95207  +#define PragTyp_TEMP_STORE                    31
        95208  +#define PragTyp_TEMP_STORE_DIRECTORY          32
        95209  +#define PragTyp_WAL_AUTOCHECKPOINT            33
        95210  +#define PragTyp_WAL_CHECKPOINT                34
        95211  +#define PragTyp_ACTIVATE_EXTENSIONS           35
        95212  +#define PragTyp_HEXKEY                        36
        95213  +#define PragTyp_KEY                           37
        95214  +#define PragTyp_REKEY                         38
        95215  +#define PragTyp_LOCK_STATUS                   39
        95216  +#define PragTyp_PARSER_TRACE                  40
        95217  +#define PragFlag_NeedSchema           0x01
        95218  +static const struct sPragmaNames {
        95219  +  const char *const zName;  /* Name of pragma */
        95220  +  u8 ePragTyp;              /* PragTyp_XXX value */
        95221  +  u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
        95222  +  u32 iArg;                 /* Extra argument */
        95223  +} aPragmaNames[] = {
        95224  +#if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
        95225  +  { /* zName:     */ "activate_extensions",
        95226  +    /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
        95227  +    /* ePragFlag: */ 0,
        95228  +    /* iArg:      */ 0 },
        95229  +#endif
        95230  +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
        95231  +  { /* zName:     */ "application_id",
        95232  +    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
        95233  +    /* ePragFlag: */ 0,
        95234  +    /* iArg:      */ 0 },
        95235  +#endif
        95236  +#if !defined(SQLITE_OMIT_AUTOVACUUM)
        95237  +  { /* zName:     */ "auto_vacuum",
        95238  +    /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
        95239  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95240  +    /* iArg:      */ 0 },
        95241  +#endif
        95242  +#if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
        95243  +  { /* zName:     */ "automatic_index",
        95244  +    /* ePragTyp:  */ PragTyp_FLAG,
        95245  +    /* ePragFlag: */ 0,
        95246  +    /* iArg:      */ SQLITE_AutoIndex },
        95247  +#endif
        95248  +  { /* zName:     */ "busy_timeout",
        95249  +    /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
        95250  +    /* ePragFlag: */ 0,
        95251  +    /* iArg:      */ 0 },
        95252  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
        95253  +  { /* zName:     */ "cache_size",
        95254  +    /* ePragTyp:  */ PragTyp_CACHE_SIZE,
        95255  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95256  +    /* iArg:      */ 0 },
        95257  +#endif
        95258  +  { /* zName:     */ "cache_spill",
        95259  +    /* ePragTyp:  */ PragTyp_FLAG,
        95260  +    /* ePragFlag: */ 0,
        95261  +    /* iArg:      */ SQLITE_CacheSpill },
        95262  +  { /* zName:     */ "case_sensitive_like",
        95263  +    /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
        95264  +    /* ePragFlag: */ 0,
        95265  +    /* iArg:      */ 0 },
        95266  +  { /* zName:     */ "checkpoint_fullfsync",
        95267  +    /* ePragTyp:  */ PragTyp_FLAG,
        95268  +    /* ePragFlag: */ 0,
        95269  +    /* iArg:      */ SQLITE_CkptFullFSync },
        95270  +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
        95271  +  { /* zName:     */ "collation_list",
        95272  +    /* ePragTyp:  */ PragTyp_COLLATION_LIST,
        95273  +    /* ePragFlag: */ 0,
        95274  +    /* iArg:      */ 0 },
        95275  +#endif
        95276  +#if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
        95277  +  { /* zName:     */ "compile_options",
        95278  +    /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
        95279  +    /* ePragFlag: */ 0,
        95280  +    /* iArg:      */ 0 },
        95281  +#endif
        95282  +  { /* zName:     */ "count_changes",
        95283  +    /* ePragTyp:  */ PragTyp_FLAG,
        95284  +    /* ePragFlag: */ 0,
        95285  +    /* iArg:      */ SQLITE_CountRows },
        95286  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
        95287  +  { /* zName:     */ "data_store_directory",
        95288  +    /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
        95289  +    /* ePragFlag: */ 0,
        95290  +    /* iArg:      */ 0 },
        95291  +#endif
        95292  +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
        95293  +  { /* zName:     */ "database_list",
        95294  +    /* ePragTyp:  */ PragTyp_DATABASE_LIST,
        95295  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95296  +    /* iArg:      */ 0 },
        95297  +#endif
        95298  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
        95299  +  { /* zName:     */ "default_cache_size",
        95300  +    /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
        95301  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95302  +    /* iArg:      */ 0 },
        95303  +#endif
        95304  +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
        95305  +  { /* zName:     */ "defer_foreign_keys",
        95306  +    /* ePragTyp:  */ PragTyp_FLAG,
        95307  +    /* ePragFlag: */ 0,
        95308  +    /* iArg:      */ SQLITE_DeferFKs },
        95309  +#endif
        95310  +  { /* zName:     */ "empty_result_callbacks",
        95311  +    /* ePragTyp:  */ PragTyp_FLAG,
        95312  +    /* ePragFlag: */ 0,
        95313  +    /* iArg:      */ SQLITE_NullCallback },
        95314  +#if !defined(SQLITE_OMIT_UTF16)
        95315  +  { /* zName:     */ "encoding",
        95316  +    /* ePragTyp:  */ PragTyp_ENCODING,
        95317  +    /* ePragFlag: */ 0,
        95318  +    /* iArg:      */ 0 },
        95319  +#endif
        95320  +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
        95321  +  { /* zName:     */ "foreign_key_check",
        95322  +    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
        95323  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95324  +    /* iArg:      */ 0 },
        95325  +#endif
        95326  +#if !defined(SQLITE_OMIT_FOREIGN_KEY)
        95327  +  { /* zName:     */ "foreign_key_list",
        95328  +    /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
        95329  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95330  +    /* iArg:      */ 0 },
        95331  +#endif
        95332  +#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
        95333  +  { /* zName:     */ "foreign_keys",
        95334  +    /* ePragTyp:  */ PragTyp_FLAG,
        95335  +    /* ePragFlag: */ 0,
        95336  +    /* iArg:      */ SQLITE_ForeignKeys },
        95337  +#endif
        95338  +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
        95339  +  { /* zName:     */ "freelist_count",
        95340  +    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
        95341  +    /* ePragFlag: */ 0,
        95342  +    /* iArg:      */ 0 },
        95343  +#endif
        95344  +  { /* zName:     */ "full_column_names",
        95345  +    /* ePragTyp:  */ PragTyp_FLAG,
        95346  +    /* ePragFlag: */ 0,
        95347  +    /* iArg:      */ SQLITE_FullColNames },
        95348  +  { /* zName:     */ "fullfsync",
        95349  +    /* ePragTyp:  */ PragTyp_FLAG,
        95350  +    /* ePragFlag: */ 0,
        95351  +    /* iArg:      */ SQLITE_FullFSync },
        95352  +#if defined(SQLITE_HAS_CODEC)
        95353  +  { /* zName:     */ "hexkey",
        95354  +    /* ePragTyp:  */ PragTyp_HEXKEY,
        95355  +    /* ePragFlag: */ 0,
        95356  +    /* iArg:      */ 0 },
        95357  +  { /* zName:     */ "hexrekey",
        95358  +    /* ePragTyp:  */ PragTyp_HEXKEY,
        95359  +    /* ePragFlag: */ 0,
        95360  +    /* iArg:      */ 0 },
        95361  +#endif
        95362  +#if !defined(SQLITE_OMIT_CHECK)
        95363  +  { /* zName:     */ "ignore_check_constraints",
        95364  +    /* ePragTyp:  */ PragTyp_FLAG,
        95365  +    /* ePragFlag: */ 0,
        95366  +    /* iArg:      */ SQLITE_IgnoreChecks },
        95367  +#endif
        95368  +#if !defined(SQLITE_OMIT_AUTOVACUUM)
        95369  +  { /* zName:     */ "incremental_vacuum",
        95370  +    /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
        95371  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95372  +    /* iArg:      */ 0 },
        95373  +#endif
        95374  +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
        95375  +  { /* zName:     */ "index_info",
        95376  +    /* ePragTyp:  */ PragTyp_INDEX_INFO,
        95377  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95378  +    /* iArg:      */ 0 },
        95379  +  { /* zName:     */ "index_list",
        95380  +    /* ePragTyp:  */ PragTyp_INDEX_LIST,
        95381  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95382  +    /* iArg:      */ 0 },
        95383  +#endif
        95384  +#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
        95385  +  { /* zName:     */ "integrity_check",
        95386  +    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
        95387  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95388  +    /* iArg:      */ 0 },
        95389  +#endif
        95390  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
        95391  +  { /* zName:     */ "journal_mode",
        95392  +    /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
        95393  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95394  +    /* iArg:      */ 0 },
        95395  +  { /* zName:     */ "journal_size_limit",
        95396  +    /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
        95397  +    /* ePragFlag: */ 0,
        95398  +    /* iArg:      */ 0 },
        95399  +#endif
        95400  +#if defined(SQLITE_HAS_CODEC)
        95401  +  { /* zName:     */ "key",
        95402  +    /* ePragTyp:  */ PragTyp_KEY,
        95403  +    /* ePragFlag: */ 0,
        95404  +    /* iArg:      */ 0 },
        95405  +#endif
        95406  +  { /* zName:     */ "legacy_file_format",
        95407  +    /* ePragTyp:  */ PragTyp_FLAG,
        95408  +    /* ePragFlag: */ 0,
        95409  +    /* iArg:      */ SQLITE_LegacyFileFmt },
        95410  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
        95411  +  { /* zName:     */ "lock_proxy_file",
        95412  +    /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
        95413  +    /* ePragFlag: */ 0,
        95414  +    /* iArg:      */ 0 },
        95415  +#endif
        95416  +#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
        95417  +  { /* zName:     */ "lock_status",
        95418  +    /* ePragTyp:  */ PragTyp_LOCK_STATUS,
        95419  +    /* ePragFlag: */ 0,
        95420  +    /* iArg:      */ 0 },
        95421  +#endif
        95422  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
        95423  +  { /* zName:     */ "locking_mode",
        95424  +    /* ePragTyp:  */ PragTyp_LOCKING_MODE,
        95425  +    /* ePragFlag: */ 0,
        95426  +    /* iArg:      */ 0 },
        95427  +  { /* zName:     */ "max_page_count",
        95428  +    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
        95429  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95430  +    /* iArg:      */ 0 },
        95431  +  { /* zName:     */ "mmap_size",
        95432  +    /* ePragTyp:  */ PragTyp_MMAP_SIZE,
        95433  +    /* ePragFlag: */ 0,
        95434  +    /* iArg:      */ 0 },
        95435  +  { /* zName:     */ "page_count",
        95436  +    /* ePragTyp:  */ PragTyp_PAGE_COUNT,
        95437  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95438  +    /* iArg:      */ 0 },
        95439  +  { /* zName:     */ "page_size",
        95440  +    /* ePragTyp:  */ PragTyp_PAGE_SIZE,
        95441  +    /* ePragFlag: */ 0,
        95442  +    /* iArg:      */ 0 },
        95443  +#endif
        95444  +#if defined(SQLITE_DEBUG)
        95445  +  { /* zName:     */ "parser_trace",
        95446  +    /* ePragTyp:  */ PragTyp_PARSER_TRACE,
        95447  +    /* ePragFlag: */ 0,
        95448  +    /* iArg:      */ 0 },
        95449  +#endif
        95450  +  { /* zName:     */ "query_only",
        95451  +    /* ePragTyp:  */ PragTyp_FLAG,
        95452  +    /* ePragFlag: */ 0,
        95453  +    /* iArg:      */ SQLITE_QueryOnly },
        95454  +#if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
        95455  +  { /* zName:     */ "quick_check",
        95456  +    /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
        95457  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95458  +    /* iArg:      */ 0 },
        95459  +#endif
        95460  +  { /* zName:     */ "read_uncommitted",
        95461  +    /* ePragTyp:  */ PragTyp_FLAG,
        95462  +    /* ePragFlag: */ 0,
        95463  +    /* iArg:      */ SQLITE_ReadUncommitted },
        95464  +  { /* zName:     */ "recursive_triggers",
        95465  +    /* ePragTyp:  */ PragTyp_FLAG,
        95466  +    /* ePragFlag: */ 0,
        95467  +    /* iArg:      */ SQLITE_RecTriggers },
        95468  +#if defined(SQLITE_HAS_CODEC)
        95469  +  { /* zName:     */ "rekey",
        95470  +    /* ePragTyp:  */ PragTyp_REKEY,
        95471  +    /* ePragFlag: */ 0,
        95472  +    /* iArg:      */ 0 },
        95473  +#endif
        95474  +  { /* zName:     */ "reverse_unordered_selects",
        95475  +    /* ePragTyp:  */ PragTyp_FLAG,
        95476  +    /* ePragFlag: */ 0,
        95477  +    /* iArg:      */ SQLITE_ReverseOrder },
        95478  +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
        95479  +  { /* zName:     */ "schema_version",
        95480  +    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
        95481  +    /* ePragFlag: */ 0,
        95482  +    /* iArg:      */ 0 },
        95483  +#endif
        95484  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
        95485  +  { /* zName:     */ "secure_delete",
        95486  +    /* ePragTyp:  */ PragTyp_SECURE_DELETE,
        95487  +    /* ePragFlag: */ 0,
        95488  +    /* iArg:      */ 0 },
        95489  +#endif
        95490  +  { /* zName:     */ "short_column_names",
        95491  +    /* ePragTyp:  */ PragTyp_FLAG,
        95492  +    /* ePragFlag: */ 0,
        95493  +    /* iArg:      */ SQLITE_ShortColNames },
        95494  +  { /* zName:     */ "shrink_memory",
        95495  +    /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
        95496  +    /* ePragFlag: */ 0,
        95497  +    /* iArg:      */ 0 },
        95498  +  { /* zName:     */ "soft_heap_limit",
        95499  +    /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
        95500  +    /* ePragFlag: */ 0,
        95501  +    /* iArg:      */ 0 },
        95502  +#if defined(SQLITE_DEBUG)
        95503  +  { /* zName:     */ "sql_trace",
        95504  +    /* ePragTyp:  */ PragTyp_FLAG,
        95505  +    /* ePragFlag: */ 0,
        95506  +    /* iArg:      */ SQLITE_SqlTrace },
        95507  +#endif
        95508  +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
        95509  +  { /* zName:     */ "stats",
        95510  +    /* ePragTyp:  */ PragTyp_STATS,
        95511  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95512  +    /* iArg:      */ 0 },
        95513  +#endif
        95514  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
        95515  +  { /* zName:     */ "synchronous",
        95516  +    /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
        95517  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95518  +    /* iArg:      */ 0 },
        95519  +#endif
        95520  +#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
        95521  +  { /* zName:     */ "table_info",
        95522  +    /* ePragTyp:  */ PragTyp_TABLE_INFO,
        95523  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95524  +    /* iArg:      */ 0 },
        95525  +#endif
        95526  +#if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
        95527  +  { /* zName:     */ "temp_store",
        95528  +    /* ePragTyp:  */ PragTyp_TEMP_STORE,
        95529  +    /* ePragFlag: */ 0,
        95530  +    /* iArg:      */ 0 },
        95531  +  { /* zName:     */ "temp_store_directory",
        95532  +    /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
        95533  +    /* ePragFlag: */ 0,
        95534  +    /* iArg:      */ 0 },
        95535  +#endif
        95536  +#if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
        95537  +  { /* zName:     */ "user_version",
        95538  +    /* ePragTyp:  */ PragTyp_HEADER_VALUE,
        95539  +    /* ePragFlag: */ 0,
        95540  +    /* iArg:      */ 0 },
        95541  +#endif
        95542  +#if defined(SQLITE_DEBUG)
        95543  +  { /* zName:     */ "vdbe_addoptrace",
        95544  +    /* ePragTyp:  */ PragTyp_FLAG,
        95545  +    /* ePragFlag: */ 0,
        95546  +    /* iArg:      */ SQLITE_VdbeAddopTrace },
        95547  +  { /* zName:     */ "vdbe_debug",
        95548  +    /* ePragTyp:  */ PragTyp_FLAG,
        95549  +    /* ePragFlag: */ 0,
        95550  +    /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
        95551  +  { /* zName:     */ "vdbe_listing",
        95552  +    /* ePragTyp:  */ PragTyp_FLAG,
        95553  +    /* ePragFlag: */ 0,
        95554  +    /* iArg:      */ SQLITE_VdbeListing },
        95555  +  { /* zName:     */ "vdbe_trace",
        95556  +    /* ePragTyp:  */ PragTyp_FLAG,
        95557  +    /* ePragFlag: */ 0,
        95558  +    /* iArg:      */ SQLITE_VdbeTrace },
        95559  +#endif
        95560  +#if !defined(SQLITE_OMIT_WAL)
        95561  +  { /* zName:     */ "wal_autocheckpoint",
        95562  +    /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
        95563  +    /* ePragFlag: */ 0,
        95564  +    /* iArg:      */ 0 },
        95565  +  { /* zName:     */ "wal_checkpoint",
        95566  +    /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
        95567  +    /* ePragFlag: */ PragFlag_NeedSchema,
        95568  +    /* iArg:      */ 0 },
        95569  +#endif
        95570  +  { /* zName:     */ "writable_schema",
        95571  +    /* ePragTyp:  */ PragTyp_FLAG,
        95572  +    /* ePragFlag: */ 0,
        95573  +    /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
        95574  +};
        95575  +/* Number of pragmas: 56 on by default, 68 total. */
        95576  +/* End of the automatically generated pragma table.
        95577  +***************************************************************************/
        95578  +
 94841  95579   /*
 94842  95580   ** Interpret the given string as a safety level.  Return 0 for OFF,
 94843  95581   ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
 94844  95582   ** unrecognized string argument.  The FULL option is disallowed
 94845  95583   ** if the omitFull parameter it 1.
 94846  95584   **
 94847  95585   ** Note that the values returned are one less that the values that
................................................................................
 95009  95747     }
 95010  95748   }
 95011  95749   #else
 95012  95750   # define setAllPagerFlags(X)  /* no-op */
 95013  95751   #endif
 95014  95752   
 95015  95753   
 95016         -#ifndef SQLITE_OMIT_FLAG_PRAGMAS
 95017         -/*
 95018         -** Check to see if zRight and zLeft refer to a pragma that queries
 95019         -** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
 95020         -** Also, implement the pragma.
 95021         -*/
 95022         -static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
 95023         -  static const struct sPragmaType {
 95024         -    const char *zName;  /* Name of the pragma */
 95025         -    int mask;           /* Mask for the db->flags value */
 95026         -  } aPragma[] = {
 95027         -    { "full_column_names",        SQLITE_FullColNames  },
 95028         -    { "short_column_names",       SQLITE_ShortColNames },
 95029         -    { "count_changes",            SQLITE_CountRows     },
 95030         -    { "empty_result_callbacks",   SQLITE_NullCallback  },
 95031         -    { "legacy_file_format",       SQLITE_LegacyFileFmt },
 95032         -    { "fullfsync",                SQLITE_FullFSync     },
 95033         -    { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
 95034         -    { "cache_spill",              SQLITE_CacheSpill    },
 95035         -    { "reverse_unordered_selects", SQLITE_ReverseOrder  },
 95036         -    { "query_only",               SQLITE_QueryOnly     },
 95037         -#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
 95038         -    { "automatic_index",          SQLITE_AutoIndex     },
 95039         -#endif
 95040         -#ifdef SQLITE_DEBUG
 95041         -    { "sql_trace",                SQLITE_SqlTrace      },
 95042         -    { "vdbe_listing",             SQLITE_VdbeListing   },
 95043         -    { "vdbe_trace",               SQLITE_VdbeTrace     },
 95044         -    { "vdbe_addoptrace",          SQLITE_VdbeAddopTrace},
 95045         -    { "vdbe_debug",    SQLITE_SqlTrace | SQLITE_VdbeListing
 95046         -                               | SQLITE_VdbeTrace      },
 95047         -#endif
 95048         -#ifndef SQLITE_OMIT_CHECK
 95049         -    { "ignore_check_constraints", SQLITE_IgnoreChecks  },
 95050         -#endif
 95051         -    /* The following is VERY experimental */
 95052         -    { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
 95053         -
 95054         -    /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
 95055         -    ** flag if there are any active statements. */
 95056         -    { "read_uncommitted",         SQLITE_ReadUncommitted },
 95057         -    { "recursive_triggers",       SQLITE_RecTriggers   },
 95058         -
 95059         -    /* This flag may only be set if both foreign-key and trigger support
 95060         -    ** are present in the build.  */
 95061         -#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
 95062         -    { "foreign_keys",             SQLITE_ForeignKeys   },
 95063         -    { "defer_foreign_keys",       SQLITE_DeferFKs      },
 95064         -#endif
 95065         -  };
 95066         -  int i;
 95067         -  const struct sPragmaType *p;
 95068         -  for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
 95069         -    if( sqlite3StrICmp(zLeft, p->zName)==0 ){
 95070         -      sqlite3 *db = pParse->db;
 95071         -      Vdbe *v;
 95072         -      v = sqlite3GetVdbe(pParse);
 95073         -      assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
 95074         -      if( ALWAYS(v) ){
 95075         -        if( zRight==0 ){
 95076         -          returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
 95077         -        }else{
 95078         -          int mask = p->mask;          /* Mask of bits to set or clear. */
 95079         -          if( db->autoCommit==0 ){
 95080         -            /* Foreign key support may not be enabled or disabled while not
 95081         -            ** in auto-commit mode.  */
 95082         -            mask &= ~(SQLITE_ForeignKeys);
 95083         -          }
 95084         -
 95085         -          if( sqlite3GetBoolean(zRight, 0) ){
 95086         -            db->flags |= mask;
 95087         -          }else{
 95088         -            db->flags &= ~mask;
 95089         -            if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
 95090         -          }
 95091         -
 95092         -          /* Many of the flag-pragmas modify the code generated by the SQL 
 95093         -          ** compiler (eg. count_changes). So add an opcode to expire all
 95094         -          ** compiled SQL statements after modifying a pragma value.
 95095         -          */
 95096         -          sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
 95097         -        }
 95098         -      }
 95099         -
 95100         -      return 1;
 95101         -    }
 95102         -  }
 95103         -  return 0;
 95104         -}
 95105         -#endif /* SQLITE_OMIT_FLAG_PRAGMAS */
 95106         -
 95107  95754   /*
 95108  95755   ** Return a human-readable name for a constraint resolution action.
 95109  95756   */
 95110  95757   #ifndef SQLITE_OMIT_FOREIGN_KEY
 95111  95758   static const char *actionName(u8 action){
 95112  95759     const char *zName;
 95113  95760     switch( action ){
................................................................................
 95169  95816     Token *pValue,      /* Token for <value>, or NULL */
 95170  95817     int minusFlag       /* True if a '-' sign preceded <value> */
 95171  95818   ){
 95172  95819     char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
 95173  95820     char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
 95174  95821     const char *zDb = 0;   /* The database name */
 95175  95822     Token *pId;            /* Pointer to <id> token */
 95176         -  int iDb;               /* Database index for <database> */
 95177  95823     char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
        95824  +  int iDb;               /* Database index for <database> */
        95825  +  int lwr, upr, mid;           /* Binary search bounds */
 95178  95826     int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
 95179  95827     sqlite3 *db = pParse->db;    /* The database connection */
 95180  95828     Db *pDb;                     /* The specific database being pragmaed */
 95181  95829     Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
 95182  95830   
 95183  95831     if( v==0 ) return;
 95184  95832     sqlite3VdbeRunOnlyOnce(v);
................................................................................
 95226  95874         int mem = ++pParse->nMem;
 95227  95875         sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
 95228  95876         sqlite3VdbeSetNumCols(v, 1);
 95229  95877         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
 95230  95878         sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
 95231  95879         sqlite3_free(aFcntl[0]);
 95232  95880       }
 95233         -  }else if( rc!=SQLITE_NOTFOUND ){
        95881  +    goto pragma_out;
        95882  +  }
        95883  +  if( rc!=SQLITE_NOTFOUND ){
 95234  95884       if( aFcntl[0] ){
 95235  95885         sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
 95236  95886         sqlite3_free(aFcntl[0]);
 95237  95887       }
 95238  95888       pParse->nErr++;
 95239  95889       pParse->rc = rc;
 95240         -  }else
 95241         -                            
 95242         - 
        95890  +    goto pragma_out;
        95891  +  }
        95892  +
        95893  +  /* Locate the pragma in the lookup table */
        95894  +  lwr = 0;
        95895  +  upr = ArraySize(aPragmaNames)-1;
        95896  +  while( lwr<=upr ){
        95897  +    mid = (lwr+upr)/2;
        95898  +    rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
        95899  +    if( rc==0 ) break;
        95900  +    if( rc<0 ){
        95901  +      upr = mid - 1;
        95902  +    }else{
        95903  +      lwr = mid + 1;
        95904  +    }
        95905  +  }
        95906  +  if( lwr>upr ) goto pragma_out;
        95907  +
        95908  +  /* Make sure the database schema is loaded if the pragma requires that */
        95909  +  if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
        95910  +    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
        95911  +  }
        95912  +
        95913  +  /* Jump to the appropriate pragma handler */
        95914  +  switch( aPragmaNames[mid].ePragTyp ){
        95915  +  
 95243  95916   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
 95244  95917     /*
 95245  95918     **  PRAGMA [database.]default_cache_size
 95246  95919     **  PRAGMA [database.]default_cache_size=N
 95247  95920     **
 95248  95921     ** The first form reports the current persistent setting for the
 95249  95922     ** page cache size.  The value returned is the maximum number of
................................................................................
 95253  95926     **
 95254  95927     ** Older versions of SQLite would set the default cache size to a
 95255  95928     ** negative number to indicate synchronous=OFF.  These days, synchronous
 95256  95929     ** is always on by default regardless of the sign of the default cache
 95257  95930     ** size.  But continue to take the absolute value of the default cache
 95258  95931     ** size of historical compatibility.
 95259  95932     */
 95260         -  if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
        95933  +  case PragTyp_DEFAULT_CACHE_SIZE: {
 95261  95934       static const VdbeOpList getCacheSize[] = {
 95262  95935         { OP_Transaction, 0, 0,        0},                         /* 0 */
 95263  95936         { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
 95264  95937         { OP_IfPos,       1, 8,        0},
 95265  95938         { OP_Integer,     0, 2,        0},
 95266  95939         { OP_Subtract,    1, 2,        1},
 95267  95940         { OP_IfPos,       1, 8,        0},
 95268  95941         { OP_Integer,     0, 1,        0},                         /* 6 */
 95269  95942         { OP_Noop,        0, 0,        0},
 95270  95943         { OP_ResultRow,   1, 1,        0},
 95271  95944       };
 95272  95945       int addr;
 95273         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 95274  95946       sqlite3VdbeUsesBtree(v, iDb);
 95275  95947       if( !zRight ){
 95276  95948         sqlite3VdbeSetNumCols(v, 1);
 95277  95949         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
 95278  95950         pParse->nMem += 2;
 95279  95951         addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
 95280  95952         sqlite3VdbeChangeP1(v, addr, iDb);
................................................................................
 95285  95957         sqlite3BeginWriteOperation(pParse, 0, iDb);
 95286  95958         sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
 95287  95959         sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
 95288  95960         assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 95289  95961         pDb->pSchema->cache_size = size;
 95290  95962         sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
 95291  95963       }
 95292         -  }else
        95964  +    break;
        95965  +  }
 95293  95966   #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
 95294  95967   
 95295  95968   #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
 95296  95969     /*
 95297  95970     **  PRAGMA [database.]page_size
 95298  95971     **  PRAGMA [database.]page_size=N
 95299  95972     **
 95300  95973     ** The first form reports the current setting for the
 95301  95974     ** database page size in bytes.  The second form sets the
 95302  95975     ** database page size value.  The value can only be set if
 95303  95976     ** the database has not yet been created.
 95304  95977     */
 95305         -  if( sqlite3StrICmp(zLeft,"page_size")==0 ){
        95978  +  case PragTyp_PAGE_SIZE: {
 95306  95979       Btree *pBt = pDb->pBt;
 95307  95980       assert( pBt!=0 );
 95308  95981       if( !zRight ){
 95309  95982         int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
 95310  95983         returnSingleInt(pParse, "page_size", size);
 95311  95984       }else{
 95312  95985         /* Malloc may fail when setting the page-size, as there is an internal
................................................................................
 95313  95986         ** buffer that the pager module resizes using sqlite3_realloc().
 95314  95987         */
 95315  95988         db->nextPagesize = sqlite3Atoi(zRight);
 95316  95989         if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
 95317  95990           db->mallocFailed = 1;
 95318  95991         }
 95319  95992       }
 95320         -  }else
        95993  +    break;
        95994  +  }
 95321  95995   
 95322  95996     /*
 95323  95997     **  PRAGMA [database.]secure_delete
 95324  95998     **  PRAGMA [database.]secure_delete=ON/OFF
 95325  95999     **
 95326  96000     ** The first form reports the current setting for the
 95327  96001     ** secure_delete flag.  The second form changes the secure_delete
 95328  96002     ** flag setting and reports thenew value.
 95329  96003     */
 95330         -  if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
        96004  +  case PragTyp_SECURE_DELETE: {
 95331  96005       Btree *pBt = pDb->pBt;
 95332  96006       int b = -1;
 95333  96007       assert( pBt!=0 );
 95334  96008       if( zRight ){
 95335  96009         b = sqlite3GetBoolean(zRight, 0);
 95336  96010       }
 95337  96011       if( pId2->n==0 && b>=0 ){
................................................................................
 95338  96012         int ii;
 95339  96013         for(ii=0; ii<db->nDb; ii++){
 95340  96014           sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
 95341  96015         }
 95342  96016       }
 95343  96017       b = sqlite3BtreeSecureDelete(pBt, b);
 95344  96018       returnSingleInt(pParse, "secure_delete", b);
 95345         -  }else
        96019  +    break;
        96020  +  }
 95346  96021   
 95347  96022     /*
 95348  96023     **  PRAGMA [database.]max_page_count
 95349  96024     **  PRAGMA [database.]max_page_count=N
 95350  96025     **
 95351  96026     ** The first form reports the current setting for the
 95352  96027     ** maximum number of pages in the database file.  The 
................................................................................
 95357  96032     ** change.  The only purpose is to provide an easy way to test
 95358  96033     ** the sqlite3AbsInt32() function.
 95359  96034     **
 95360  96035     **  PRAGMA [database.]page_count
 95361  96036     **
 95362  96037     ** Return the number of pages in the specified database.
 95363  96038     */
 95364         -  if( sqlite3StrICmp(zLeft,"page_count")==0
 95365         -   || sqlite3StrICmp(zLeft,"max_page_count")==0
 95366         -  ){
        96039  +  case PragTyp_PAGE_COUNT: {
 95367  96040       int iReg;
 95368         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 95369  96041       sqlite3CodeVerifySchema(pParse, iDb);
 95370  96042       iReg = ++pParse->nMem;
 95371  96043       if( sqlite3Tolower(zLeft[0])=='p' ){
 95372  96044         sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
 95373  96045       }else{
 95374  96046         sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
 95375  96047                           sqlite3AbsInt32(sqlite3Atoi(zRight)));
 95376  96048       }
 95377  96049       sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
 95378  96050       sqlite3VdbeSetNumCols(v, 1);
 95379  96051       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
 95380         -  }else
        96052  +    break;
        96053  +  }
 95381  96054   
 95382  96055     /*
 95383  96056     **  PRAGMA [database.]locking_mode
 95384  96057     **  PRAGMA [database.]locking_mode = (normal|exclusive)
 95385  96058     */
 95386         -  if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
        96059  +  case PragTyp_LOCKING_MODE: {
 95387  96060       const char *zRet = "normal";
 95388  96061       int eMode = getLockingMode(zRight);
 95389  96062   
 95390  96063       if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
 95391  96064         /* Simple "PRAGMA locking_mode;" statement. This is a query for
 95392  96065         ** the current default locking mode (which may be different to
 95393  96066         ** the locking-mode of the main database).
................................................................................
 95412  96085           }
 95413  96086           db->dfltLockMode = (u8)eMode;
 95414  96087         }
 95415  96088         pPager = sqlite3BtreePager(pDb->pBt);
 95416  96089         eMode = sqlite3PagerLockingMode(pPager, eMode);
 95417  96090       }
 95418  96091   
 95419         -    assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
        96092  +    assert( eMode==PAGER_LOCKINGMODE_NORMAL
        96093  +            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
 95420  96094       if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
 95421  96095         zRet = "exclusive";
 95422  96096       }
 95423  96097       sqlite3VdbeSetNumCols(v, 1);
 95424  96098       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
 95425  96099       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
 95426  96100       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 95427         -  }else
        96101  +    break;
        96102  +  }
 95428  96103   
 95429  96104     /*
 95430  96105     **  PRAGMA [database.]journal_mode
 95431  96106     **  PRAGMA [database.]journal_mode =
 95432  96107     **                      (delete|persist|off|truncate|memory|wal|off)
 95433  96108     */
 95434         -  if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
        96109  +  case PragTyp_JOURNAL_MODE: {
 95435  96110       int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
 95436  96111       int ii;           /* Loop counter */
 95437  96112   
 95438         -    /* Force the schema to be loaded on all databases.  This causes all
 95439         -    ** database files to be opened and the journal_modes set.  This is
 95440         -    ** necessary because subsequent processing must know if the databases
 95441         -    ** are in WAL mode. */
 95442         -    if( sqlite3ReadSchema(pParse) ){
 95443         -      goto pragma_out;
 95444         -    }
 95445         -
 95446  96113       sqlite3VdbeSetNumCols(v, 1);
 95447  96114       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
 95448  96115   
 95449  96116       if( zRight==0 ){
 95450  96117         /* If there is no "=MODE" part of the pragma, do a query for the
 95451  96118         ** current mode */
 95452  96119         eMode = PAGER_JOURNALMODE_QUERY;
................................................................................
 95470  96137       for(ii=db->nDb-1; ii>=0; ii--){
 95471  96138         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
 95472  96139           sqlite3VdbeUsesBtree(v, ii);
 95473  96140           sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
 95474  96141         }
 95475  96142       }
 95476  96143       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 95477         -  }else
        96144  +    break;
        96145  +  }
 95478  96146   
 95479  96147     /*
 95480  96148     **  PRAGMA [database.]journal_size_limit
 95481  96149     **  PRAGMA [database.]journal_size_limit=N
 95482  96150     **
 95483  96151     ** Get or set the size limit on rollback journal files.
 95484  96152     */
 95485         -  if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
        96153  +  case PragTyp_JOURNAL_SIZE_LIMIT: {
 95486  96154       Pager *pPager = sqlite3BtreePager(pDb->pBt);
 95487  96155       i64 iLimit = -2;
 95488  96156       if( zRight ){
 95489  96157         sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
 95490  96158         if( iLimit<-1 ) iLimit = -1;
 95491  96159       }
 95492  96160       iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
 95493  96161       returnSingleInt(pParse, "journal_size_limit", iLimit);
 95494         -  }else
        96162  +    break;
        96163  +  }
 95495  96164   
 95496  96165   #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
 95497  96166   
 95498  96167     /*
 95499  96168     **  PRAGMA [database.]auto_vacuum
 95500  96169     **  PRAGMA [database.]auto_vacuum=N
 95501  96170     **
 95502  96171     ** Get or set the value of the database 'auto-vacuum' parameter.
 95503  96172     ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
 95504  96173     */
 95505  96174   #ifndef SQLITE_OMIT_AUTOVACUUM
 95506         -  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
        96175  +  case PragTyp_AUTO_VACUUM: {
 95507  96176       Btree *pBt = pDb->pBt;
 95508  96177       assert( pBt!=0 );
 95509         -    if( sqlite3ReadSchema(pParse) ){
 95510         -      goto pragma_out;
 95511         -    }
 95512  96178       if( !zRight ){
 95513         -      int auto_vacuum;
 95514         -      if( ALWAYS(pBt) ){
 95515         -         auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
 95516         -      }else{
 95517         -         auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
 95518         -      }
 95519         -      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
        96179  +      returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
 95520  96180       }else{
 95521  96181         int eAuto = getAutoVacuum(zRight);
 95522  96182         assert( eAuto>=0 && eAuto<=2 );
 95523  96183         db->nextAutovac = (u8)eAuto;
 95524         -      if( ALWAYS(eAuto>=0) ){
 95525         -        /* Call SetAutoVacuum() to set initialize the internal auto and
 95526         -        ** incr-vacuum flags. This is required in case this connection
 95527         -        ** creates the database file. It is important that it is created
 95528         -        ** as an auto-vacuum capable db.
 95529         -        */
 95530         -        rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
 95531         -        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
 95532         -          /* When setting the auto_vacuum mode to either "full" or 
 95533         -          ** "incremental", write the value of meta[6] in the database
 95534         -          ** file. Before writing to meta[6], check that meta[3] indicates
 95535         -          ** that this really is an auto-vacuum capable database.
 95536         -          */
 95537         -          static const VdbeOpList setMeta6[] = {
 95538         -            { OP_Transaction,    0,         1,                 0},    /* 0 */
 95539         -            { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
 95540         -            { OP_If,             1,         0,                 0},    /* 2 */
 95541         -            { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
 95542         -            { OP_Integer,        0,         1,                 0},    /* 4 */
 95543         -            { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
 95544         -          };
 95545         -          int iAddr;
 95546         -          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
 95547         -          sqlite3VdbeChangeP1(v, iAddr, iDb);
 95548         -          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
 95549         -          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
 95550         -          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
 95551         -          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
 95552         -          sqlite3VdbeUsesBtree(v, iDb);
 95553         -        }
 95554         -      }
 95555         -    }
 95556         -  }else
        96184  +      /* Call SetAutoVacuum() to set initialize the internal auto and
        96185  +      ** incr-vacuum flags. This is required in case this connection
        96186  +      ** creates the database file. It is important that it is created
        96187  +      ** as an auto-vacuum capable db.
        96188  +      */
        96189  +      rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
        96190  +      if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
        96191  +        /* When setting the auto_vacuum mode to either "full" or 
        96192  +        ** "incremental", write the value of meta[6] in the database
        96193  +        ** file. Before writing to meta[6], check that meta[3] indicates
        96194  +        ** that this really is an auto-vacuum capable database.
        96195  +        */
        96196  +        static const VdbeOpList setMeta6[] = {
        96197  +          { OP_Transaction,    0,         1,                 0},    /* 0 */
        96198  +          { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
        96199  +          { OP_If,             1,         0,                 0},    /* 2 */
        96200  +          { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
        96201  +          { OP_Integer,        0,         1,                 0},    /* 4 */
        96202  +          { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
        96203  +        };
        96204  +        int iAddr;
        96205  +        iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
        96206  +        sqlite3VdbeChangeP1(v, iAddr, iDb);
        96207  +        sqlite3VdbeChangeP1(v, iAddr+1, iDb);
        96208  +        sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
        96209  +        sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
        96210  +        sqlite3VdbeChangeP1(v, iAddr+5, iDb);
        96211  +        sqlite3VdbeUsesBtree(v, iDb);
        96212  +      }
        96213  +    }
        96214  +    break;
        96215  +  }
 95557  96216   #endif
 95558  96217   
 95559  96218     /*
 95560  96219     **  PRAGMA [database.]incremental_vacuum(N)
 95561  96220     **
 95562  96221     ** Do N steps of incremental vacuuming on a database.
 95563  96222     */
 95564  96223   #ifndef SQLITE_OMIT_AUTOVACUUM
 95565         -  if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
        96224  +  case PragTyp_INCREMENTAL_VACUUM: {
 95566  96225       int iLimit, addr;
 95567         -    if( sqlite3ReadSchema(pParse) ){
 95568         -      goto pragma_out;
 95569         -    }
 95570  96226       if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
 95571  96227         iLimit = 0x7fffffff;
 95572  96228       }
 95573  96229       sqlite3BeginWriteOperation(pParse, 0, iDb);
 95574  96230       sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
 95575  96231       addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
 95576  96232       sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
 95577  96233       sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
 95578  96234       sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
 95579  96235       sqlite3VdbeJumpHere(v, addr);
 95580         -  }else
        96236  +    break;
        96237  +  }
 95581  96238   #endif
 95582  96239   
 95583  96240   #ifndef SQLITE_OMIT_PAGER_PRAGMAS
 95584  96241     /*
 95585  96242     **  PRAGMA [database.]cache_size
 95586  96243     **  PRAGMA [database.]cache_size=N
 95587  96244     **
................................................................................
 95588  96245     ** The first form reports the current local setting for the
 95589  96246     ** page cache size. The second form sets the local
 95590  96247     ** page cache size value.  If N is positive then that is the
 95591  96248     ** number of pages in the cache.  If N is negative, then the
 95592  96249     ** number of pages is adjusted so that the cache uses -N kibibytes
 95593  96250     ** of memory.
 95594  96251     */
 95595         -  if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
 95596         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
        96252  +  case PragTyp_CACHE_SIZE: {
 95597  96253       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 95598  96254       if( !zRight ){
 95599  96255         returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
 95600  96256       }else{
 95601  96257         int size = sqlite3Atoi(zRight);
 95602  96258         pDb->pSchema->cache_size = size;
 95603  96259         sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
 95604  96260       }
 95605         -  }else
        96261  +    break;
        96262  +  }
 95606  96263   
 95607  96264     /*
 95608  96265     **  PRAGMA [database.]mmap_size(N)
 95609  96266     **
 95610  96267     ** Used to set mapping size limit. The mapping size limit is
 95611  96268     ** used to limit the aggregate size of all memory mapped regions of the
 95612  96269     ** database file. If this parameter is set to zero, then memory mapping
................................................................................
 95614  96271     ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
 95615  96272     ** The parameter N is measured in bytes.
 95616  96273     **
 95617  96274     ** This value is advisory.  The underlying VFS is free to memory map
 95618  96275     ** as little or as much as it wants.  Except, if N is set to 0 then the
 95619  96276     ** upper layers will never invoke the xFetch interfaces to the VFS.
 95620  96277     */
 95621         -  if( sqlite3StrICmp(zLeft,"mmap_size")==0 ){
        96278  +  case PragTyp_MMAP_SIZE: {
 95622  96279       sqlite3_int64 sz;
 95623  96280   #if SQLITE_MAX_MMAP_SIZE>0
 95624  96281       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
 95625  96282       if( zRight ){
 95626  96283         int ii;
 95627  96284         sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
 95628  96285         if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
................................................................................
 95641  96298   #endif
 95642  96299       if( rc==SQLITE_OK ){
 95643  96300         returnSingleInt(pParse, "mmap_size", sz);
 95644  96301       }else if( rc!=SQLITE_NOTFOUND ){
 95645  96302         pParse->nErr++;
 95646  96303         pParse->rc = rc;
 95647  96304       }
 95648         -  }else
        96305  +    break;
        96306  +  }
 95649  96307   
 95650  96308     /*
 95651  96309     **   PRAGMA temp_store
 95652  96310     **   PRAGMA temp_store = "default"|"memory"|"file"
 95653  96311     **
 95654  96312     ** Return or set the local value of the temp_store flag.  Changing
 95655  96313     ** the local value does not make changes to the disk file and the default
 95656  96314     ** value will be restored the next time the database is opened.
 95657  96315     **
 95658  96316     ** Note that it is possible for the library compile-time options to
 95659  96317     ** override this setting
 95660  96318     */
 95661         -  if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
        96319  +  case PragTyp_TEMP_STORE: {
 95662  96320       if( !zRight ){
 95663  96321         returnSingleInt(pParse, "temp_store", db->temp_store);
 95664  96322       }else{
 95665  96323         changeTempStorage(pParse, zRight);
 95666  96324       }
 95667         -  }else
        96325  +    break;
        96326  +  }
 95668  96327   
 95669  96328     /*
 95670  96329     **   PRAGMA temp_store_directory
 95671  96330     **   PRAGMA temp_store_directory = ""|"directory_name"
 95672  96331     **
 95673  96332     ** Return or set the local value of the temp_store_directory flag.  Changing
 95674  96333     ** the value sets a specific directory to be used for temporary files.
 95675  96334     ** Setting to a null string reverts to the default temporary directory search.
 95676  96335     ** If temporary directory is changed, then invalidateTempStorage.
 95677  96336     **
 95678  96337     */
 95679         -  if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
        96338  +  case PragTyp_TEMP_STORE_DIRECTORY: {
 95680  96339       if( !zRight ){
 95681  96340         if( sqlite3_temp_directory ){
 95682  96341           sqlite3VdbeSetNumCols(v, 1);
 95683  96342           sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
 95684  96343               "temp_store_directory", SQLITE_STATIC);
 95685  96344           sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
 95686  96345           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
................................................................................
 95705  96364         if( zRight[0] ){
 95706  96365           sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
 95707  96366         }else{
 95708  96367           sqlite3_temp_directory = 0;
 95709  96368         }
 95710  96369   #endif /* SQLITE_OMIT_WSD */
 95711  96370       }
 95712         -  }else
        96371  +    break;
        96372  +  }
 95713  96373   
 95714  96374   #if SQLITE_OS_WIN
 95715  96375     /*
 95716  96376     **   PRAGMA data_store_directory
 95717  96377     **   PRAGMA data_store_directory = ""|"directory_name"
 95718  96378     **
 95719  96379     ** Return or set the local value of the data_store_directory flag.  Changing
................................................................................
 95721  96381     ** were specified with a relative pathname.  Setting to a null string reverts
 95722  96382     ** to the default database directory, which for database files specified with
 95723  96383     ** a relative path will probably be based on the current directory for the
 95724  96384     ** process.  Database file specified with an absolute path are not impacted
 95725  96385     ** by this setting, regardless of its value.
 95726  96386     **
 95727  96387     */
 95728         -  if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
        96388  +  case PragTyp_DATA_STORE_DIRECTORY: {
 95729  96389       if( !zRight ){
 95730  96390         if( sqlite3_data_directory ){
 95731  96391           sqlite3VdbeSetNumCols(v, 1);
 95732  96392           sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
 95733  96393               "data_store_directory", SQLITE_STATIC);
 95734  96394           sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
 95735  96395           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
................................................................................
 95748  96408         if( zRight[0] ){
 95749  96409           sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
 95750  96410         }else{
 95751  96411           sqlite3_data_directory = 0;
 95752  96412         }
 95753  96413   #endif /* SQLITE_OMIT_WSD */
 95754  96414       }
 95755         -  }else
        96415  +    break;
        96416  +  }
 95756  96417   #endif
 95757  96418   
 95758         -#if !defined(SQLITE_ENABLE_LOCKING_STYLE)
 95759         -#  if defined(__APPLE__)
 95760         -#    define SQLITE_ENABLE_LOCKING_STYLE 1
 95761         -#  else
 95762         -#    define SQLITE_ENABLE_LOCKING_STYLE 0
 95763         -#  endif
 95764         -#endif
 95765  96419   #if SQLITE_ENABLE_LOCKING_STYLE
 95766  96420     /*
 95767         -   **   PRAGMA [database.]lock_proxy_file
 95768         -   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
 95769         -   **
 95770         -   ** Return or set the value of the lock_proxy_file flag.  Changing
 95771         -   ** the value sets a specific file to be used for database access locks.
 95772         -   **
 95773         -   */
 95774         -  if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
        96421  +  **   PRAGMA [database.]lock_proxy_file
        96422  +  **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
        96423  +  **
        96424  +  ** Return or set the value of the lock_proxy_file flag.  Changing
        96425  +  ** the value sets a specific file to be used for database access locks.
        96426  +  **
        96427  +  */
        96428  +  case PragTyp_LOCK_PROXY_FILE: {
 95775  96429       if( !zRight ){
 95776  96430         Pager *pPager = sqlite3BtreePager(pDb->pBt);
 95777  96431         char *proxy_file_path = NULL;
 95778  96432         sqlite3_file *pFile = sqlite3PagerFile(pPager);
 95779  96433         sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
 95780  96434                              &proxy_file_path);
 95781  96435         
................................................................................
 95798  96452                                        NULL);
 95799  96453         }
 95800  96454         if( res!=SQLITE_OK ){
 95801  96455           sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
 95802  96456           goto pragma_out;
 95803  96457         }
 95804  96458       }
 95805         -  }else
        96459  +    break;
        96460  +  }
 95806  96461   #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
 95807  96462       
 95808  96463     /*
 95809  96464     **   PRAGMA [database.]synchronous
 95810  96465     **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
 95811  96466     **
 95812  96467     ** Return or set the local value of the synchronous flag.  Changing
 95813  96468     ** the local value does not make changes to the disk file and the
 95814  96469     ** default value will be restored the next time the database is
 95815  96470     ** opened.
 95816  96471     */
 95817         -  if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
 95818         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
        96472  +  case PragTyp_SYNCHRONOUS: {
 95819  96473       if( !zRight ){
 95820  96474         returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
 95821  96475       }else{
 95822  96476         if( !db->autoCommit ){
 95823  96477           sqlite3ErrorMsg(pParse, 
 95824  96478               "Safety level may not be changed inside a transaction");
 95825  96479         }else{
 95826  96480           pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
 95827  96481           setAllPagerFlags(db);
 95828  96482         }
 95829  96483       }
 95830         -  }else
        96484  +    break;
        96485  +  }
 95831  96486   #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
 95832  96487   
 95833  96488   #ifndef SQLITE_OMIT_FLAG_PRAGMAS
 95834         -  if( flagPragma(pParse, zLeft, zRight) ){
 95835         -    setAllPagerFlags(db);
 95836         -  }else
        96489  +  case PragTyp_FLAG: {
        96490  +    if( zRight==0 ){
        96491  +      returnSingleInt(pParse, aPragmaNames[mid].zName,
        96492  +                     (db->flags & aPragmaNames[mid].iArg)!=0 );
        96493  +    }else{
        96494  +      int mask = aPragmaNames[mid].iArg;    /* Mask of bits to set or clear. */
        96495  +      if( db->autoCommit==0 ){
        96496  +        /* Foreign key support may not be enabled or disabled while not
        96497  +        ** in auto-commit mode.  */
        96498  +        mask &= ~(SQLITE_ForeignKeys);
        96499  +      }
        96500  +
        96501  +      if( sqlite3GetBoolean(zRight, 0) ){
        96502  +        db->flags |= mask;
        96503  +      }else{
        96504  +        db->flags &= ~mask;
        96505  +        if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
        96506  +      }
        96507  +
        96508  +      /* Many of the flag-pragmas modify the code generated by the SQL 
        96509  +      ** compiler (eg. count_changes). So add an opcode to expire all
        96510  +      ** compiled SQL statements after modifying a pragma value.
        96511  +      */
        96512  +      sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
        96513  +      setAllPagerFlags(db);
        96514  +    }
        96515  +    break;
        96516  +  }
 95837  96517   #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
 95838  96518   
 95839  96519   #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
 95840  96520     /*
 95841  96521     **   PRAGMA table_info(<table>)
 95842  96522     **
 95843  96523     ** Return a single row for each column of the named table. The columns of
................................................................................
 95845  96525     **
 95846  96526     ** cid:        Column id (numbered from left to right, starting at 0)
 95847  96527     ** name:       Column name
 95848  96528     ** type:       Column declaration type.
 95849  96529     ** notnull:    True if 'NOT NULL' is part of column declaration
 95850  96530     ** dflt_value: The default value for the column, if any.
 95851  96531     */
 95852         -  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
        96532  +  case PragTyp_TABLE_INFO: if( zRight ){
 95853  96533       Table *pTab;
 95854         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 95855  96534       pTab = sqlite3FindTable(db, zRight, zDb);
 95856  96535       if( pTab ){
 95857  96536         int i, k;
 95858  96537         int nHidden = 0;
 95859  96538         Column *pCol;
 95860  96539         Index *pPk;
 95861  96540         for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
................................................................................
 95891  96570           }else{
 95892  96571             for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
 95893  96572           }
 95894  96573           sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
 95895  96574           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
 95896  96575         }
 95897  96576       }
 95898         -  }else
        96577  +  }
        96578  +  break;
 95899  96579   
 95900         -  if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
        96580  +  case PragTyp_STATS: {
        96581  +    Index *pIdx;
        96582  +    HashElem *i;
        96583  +    v = sqlite3GetVdbe(pParse);
        96584  +    sqlite3VdbeSetNumCols(v, 4);
        96585  +    pParse->nMem = 4;
        96586  +    sqlite3CodeVerifySchema(pParse, iDb);
        96587  +    sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
        96588  +    sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
        96589  +    sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
        96590  +    sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
        96591  +    for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
        96592  +      Table *pTab = sqliteHashData(i);
        96593  +      sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
        96594  +      sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
        96595  +      sqlite3VdbeAddOp2(v, OP_Integer,
        96596  +                           (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
        96597  +      sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4);
        96598  +      sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
        96599  +      for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
        96600  +        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
        96601  +        sqlite3VdbeAddOp2(v, OP_Integer,
        96602  +                             (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
        96603  +        sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4);
        96604  +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
        96605  +      }
        96606  +    }
        96607  +  }
        96608  +  break;
        96609  +
        96610  +  case PragTyp_INDEX_INFO: if( zRight ){
 95901  96611       Index *pIdx;
 95902  96612       Table *pTab;
 95903         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 95904  96613       pIdx = sqlite3FindIndex(db, zRight, zDb);
 95905  96614       if( pIdx ){
 95906  96615         int i;
 95907  96616         pTab = pIdx->pTable;
 95908  96617         sqlite3VdbeSetNumCols(v, 3);
 95909  96618         pParse->nMem = 3;
 95910  96619         sqlite3CodeVerifySchema(pParse, iDb);
................................................................................
 95916  96625           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
 95917  96626           sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
 95918  96627           assert( pTab->nCol>cnum );
 95919  96628           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
 95920  96629           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
 95921  96630         }
 95922  96631       }
 95923         -  }else
        96632  +  }
        96633  +  break;
 95924  96634   
 95925         -  if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
        96635  +  case PragTyp_INDEX_LIST: if( zRight ){
 95926  96636       Index *pIdx;
 95927  96637       Table *pTab;
 95928         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
        96638  +    int i;
 95929  96639       pTab = sqlite3FindTable(db, zRight, zDb);
 95930  96640       if( pTab ){
 95931  96641         v = sqlite3GetVdbe(pParse);
 95932         -      pIdx = pTab->pIndex;
 95933         -      if( pIdx ){
 95934         -        int i = 0; 
 95935         -        sqlite3VdbeSetNumCols(v, 3);
 95936         -        pParse->nMem = 3;
 95937         -        sqlite3CodeVerifySchema(pParse, iDb);
 95938         -        sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
 95939         -        sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
 95940         -        sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
 95941         -        while(pIdx){
 95942         -          sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
 95943         -          sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
 95944         -          sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
 95945         -          sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
 95946         -          ++i;
 95947         -          pIdx = pIdx->pNext;
 95948         -        }
 95949         -      }
 95950         -    }
 95951         -  }else
 95952         -
 95953         -  if( sqlite3StrICmp(zLeft, "database_list")==0 ){
 95954         -    int i;
 95955         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
        96642  +      sqlite3VdbeSetNumCols(v, 3);
        96643  +      pParse->nMem = 3;
        96644  +      sqlite3CodeVerifySchema(pParse, iDb);
        96645  +      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
        96646  +      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
        96647  +      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
        96648  +      for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
        96649  +        sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
        96650  +        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
        96651  +        sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
        96652  +        sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
        96653  +      }
        96654  +    }
        96655  +  }
        96656  +  break;
        96657  +
        96658  +  case PragTyp_DATABASE_LIST: {
        96659  +    int i;
 95956  96660       sqlite3VdbeSetNumCols(v, 3);
 95957  96661       pParse->nMem = 3;
 95958  96662       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
 95959  96663       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
 95960  96664       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
 95961  96665       for(i=0; i<db->nDb; i++){
 95962  96666         if( db->aDb[i].pBt==0 ) continue;
................................................................................
 95963  96667         assert( db->aDb[i].zName!=0 );
 95964  96668         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
 95965  96669         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
 95966  96670         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
 95967  96671              sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
 95968  96672         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
 95969  96673       }
 95970         -  }else
        96674  +  }
        96675  +  break;
 95971  96676   
 95972         -  if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
        96677  +  case PragTyp_COLLATION_LIST: {
 95973  96678       int i = 0;
 95974  96679       HashElem *p;
 95975  96680       sqlite3VdbeSetNumCols(v, 2);
 95976  96681       pParse->nMem = 2;
 95977  96682       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
 95978  96683       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
 95979  96684       for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
 95980  96685         CollSeq *pColl = (CollSeq *)sqliteHashData(p);
 95981  96686         sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
 95982  96687         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
 95983  96688         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
 95984  96689       }
 95985         -  }else
        96690  +  }
        96691  +  break;
 95986  96692   #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
 95987  96693   
 95988  96694   #ifndef SQLITE_OMIT_FOREIGN_KEY
 95989         -  if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
        96695  +  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
 95990  96696       FKey *pFK;
 95991  96697       Table *pTab;
 95992         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 95993  96698       pTab = sqlite3FindTable(db, zRight, zDb);
 95994  96699       if( pTab ){
 95995  96700         v = sqlite3GetVdbe(pParse);
 95996  96701         pFK = pTab->pFKey;
 95997  96702         if( pFK ){
 95998  96703           int i = 0; 
 95999  96704           sqlite3VdbeSetNumCols(v, 8);
................................................................................
 96025  96730               sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
 96026  96731             }
 96027  96732             ++i;
 96028  96733             pFK = pFK->pNextFrom;
 96029  96734           }
 96030  96735         }
 96031  96736       }
 96032         -  }else
        96737  +  }
        96738  +  break;
 96033  96739   #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
 96034  96740   
 96035  96741   #ifndef SQLITE_OMIT_FOREIGN_KEY
 96036  96742   #ifndef SQLITE_OMIT_TRIGGER
 96037         -  if( sqlite3StrICmp(zLeft, "foreign_key_check")==0 ){
        96743  +  case PragTyp_FOREIGN_KEY_CHECK: {
 96038  96744       FKey *pFK;             /* A foreign key constraint */
 96039  96745       Table *pTab;           /* Child table contain "REFERENCES" keyword */
 96040  96746       Table *pParent;        /* Parent table that child points to */
 96041  96747       Index *pIdx;           /* Index in the parent table */
 96042  96748       int i;                 /* Loop counter:  Foreign key number for pTab */
 96043  96749       int j;                 /* Loop counter:  Field of the foreign key */
 96044  96750       HashElem *k;           /* Loop counter:  Next table in schema */
................................................................................
 96046  96752       int regResult;         /* 3 registers to hold a result row */
 96047  96753       int regKey;            /* Register to hold key for checking the FK */
 96048  96754       int regRow;            /* Registers to hold a row from pTab */
 96049  96755       int addrTop;           /* Top of a loop checking foreign keys */
 96050  96756       int addrOk;            /* Jump here if the key is OK */
 96051  96757       int *aiCols;           /* child to parent column mapping */
 96052  96758   
 96053         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 96054  96759       regResult = pParse->nMem+1;
 96055  96760       pParse->nMem += 4;
 96056  96761       regKey = ++pParse->nMem;
 96057  96762       regRow = ++pParse->nMem;
 96058  96763       v = sqlite3GetVdbe(pParse);
 96059  96764       sqlite3VdbeSetNumCols(v, 4);
 96060  96765       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
................................................................................
 96140  96845           sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
 96141  96846           sqlite3VdbeResolveLabel(v, addrOk);
 96142  96847           sqlite3DbFree(db, aiCols);
 96143  96848         }
 96144  96849         sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
 96145  96850         sqlite3VdbeJumpHere(v, addrTop);
 96146  96851       }
 96147         -  }else
        96852  +  }
        96853  +  break;
 96148  96854   #endif /* !defined(SQLITE_OMIT_TRIGGER) */
 96149  96855   #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
 96150  96856   
 96151  96857   #ifndef NDEBUG
 96152         -  if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
        96858  +  case PragTyp_PARSER_TRACE: {
 96153  96859       if( zRight ){
 96154  96860         if( sqlite3GetBoolean(zRight, 0) ){
 96155  96861           sqlite3ParserTrace(stderr, "parser: ");
 96156  96862         }else{
 96157  96863           sqlite3ParserTrace(0, 0);
 96158  96864         }
 96159  96865       }
 96160         -  }else
        96866  +  }
        96867  +  break;
 96161  96868   #endif
 96162  96869   
 96163  96870     /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
 96164  96871     ** used will be case sensitive or not depending on the RHS.
 96165  96872     */
 96166         -  if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
        96873  +  case PragTyp_CASE_SENSITIVE_LIKE: {
 96167  96874       if( zRight ){
 96168  96875         sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
 96169  96876       }
 96170         -  }else
        96877  +  }
        96878  +  break;
 96171  96879   
 96172  96880   #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
 96173  96881   # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
 96174  96882   #endif
 96175  96883   
 96176  96884   #ifndef SQLITE_OMIT_INTEGRITY_CHECK
 96177  96885     /* Pragma "quick_check" is reduced version of 
 96178  96886     ** integrity_check designed to detect most database corruption
 96179  96887     ** without most of the overhead of a full integrity-check.
 96180  96888     */
 96181         -  if( sqlite3StrICmp(zLeft, "integrity_check")==0
 96182         -   || sqlite3StrICmp(zLeft, "quick_check")==0 
 96183         -  ){
        96889  +  case PragTyp_INTEGRITY_CHECK: {
 96184  96890       int i, j, addr, mxErr;
 96185  96891   
 96186  96892       /* Code that appears at the end of the integrity check.  If no error
 96187  96893       ** messages have been generated, output OK.  Otherwise output the
 96188  96894       ** error message
 96189  96895       */
 96190  96896       static const VdbeOpList endCode[] = {
................................................................................
 96206  96912       ** to -1 here, to indicate that the VDBE should verify the integrity
 96207  96913       ** of all attached databases.  */
 96208  96914       assert( iDb>=0 );
 96209  96915       assert( iDb==0 || pId2->z );
 96210  96916       if( pId2->z==0 ) iDb = -1;
 96211  96917   
 96212  96918       /* Initialize the VDBE program */
 96213         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 96214  96919       pParse->nMem = 6;
 96215  96920       sqlite3VdbeSetNumCols(v, 1);
 96216  96921       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
 96217  96922   
 96218  96923       /* Set the maximum error count */
 96219  96924       mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
 96220  96925       if( zRight ){
................................................................................
 96336  97041   #endif /* SQLITE_OMIT_BTREECOUNT */
 96337  97042         } 
 96338  97043       }
 96339  97044       addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
 96340  97045       sqlite3VdbeChangeP2(v, addr, -mxErr);
 96341  97046       sqlite3VdbeJumpHere(v, addr+1);
 96342  97047       sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
 96343         -  }else
        97048  +  }
        97049  +  break;
 96344  97050   #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
 96345  97051   
 96346  97052   #ifndef SQLITE_OMIT_UTF16
 96347  97053     /*
 96348  97054     **   PRAGMA encoding
 96349  97055     **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
 96350  97056     **
................................................................................
 96362  97068     ** the main database has not been initialized and/or created when ATTACH
 96363  97069     ** is executed, this is done before the ATTACH operation.
 96364  97070     **
 96365  97071     ** In the second form this pragma sets the text encoding to be used in
 96366  97072     ** new database files created using this database handle. It is only
 96367  97073     ** useful if invoked immediately after the main database i
 96368  97074     */
 96369         -  if( sqlite3StrICmp(zLeft, "encoding")==0 ){
        97075  +  case PragTyp_ENCODING: {
 96370  97076       static const struct EncName {
 96371  97077         char *zName;
 96372  97078         u8 enc;
 96373  97079       } encnames[] = {
 96374  97080         { "UTF8",     SQLITE_UTF8        },
 96375  97081         { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
 96376  97082         { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
................................................................................
 96409  97115             }
 96410  97116           }
 96411  97117           if( !pEnc->zName ){
 96412  97118             sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
 96413  97119           }
 96414  97120         }
 96415  97121       }
 96416         -  }else
        97122  +  }
        97123  +  break;
 96417  97124   #endif /* SQLITE_OMIT_UTF16 */
 96418  97125   
 96419  97126   #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
 96420  97127     /*
 96421  97128     **   PRAGMA [database.]schema_version
 96422  97129     **   PRAGMA [database.]schema_version = <integer>
 96423  97130     **
................................................................................
 96443  97150     ** Subverting this mechanism by using "PRAGMA schema_version" to modify
 96444  97151     ** the schema-version is potentially dangerous and may lead to program
 96445  97152     ** crashes or database corruption. Use with caution!
 96446  97153     **
 96447  97154     ** The user-version is not used internally by SQLite. It may be used by
 96448  97155     ** applications for any purpose.
 96449  97156     */
 96450         -  if( sqlite3StrICmp(zLeft, "schema_version")==0 
 96451         -   || sqlite3StrICmp(zLeft, "user_version")==0 
 96452         -   || sqlite3StrICmp(zLeft, "freelist_count")==0 
 96453         -   || sqlite3StrICmp(zLeft, "application_id")==0 
 96454         -  ){
        97157  +  case PragTyp_HEADER_VALUE: {
 96455  97158       int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
 96456  97159       sqlite3VdbeUsesBtree(v, iDb);
 96457  97160       switch( zLeft[0] ){
 96458  97161         case 'a': case 'A':
 96459  97162           iCookie = BTREE_APPLICATION_ID;
 96460  97163           break;
 96461  97164         case 'f': case 'F':
................................................................................
 96491  97194         int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
 96492  97195         sqlite3VdbeChangeP1(v, addr, iDb);
 96493  97196         sqlite3VdbeChangeP1(v, addr+1, iDb);
 96494  97197         sqlite3VdbeChangeP3(v, addr+1, iCookie);
 96495  97198         sqlite3VdbeSetNumCols(v, 1);
 96496  97199         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
 96497  97200       }
 96498         -  }else
        97201  +  }
        97202  +  break;
 96499  97203   #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
 96500  97204   
 96501  97205   #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
 96502  97206     /*
 96503  97207     **   PRAGMA compile_options
 96504  97208     **
 96505  97209     ** Return the names of all compile-time options used in this build,
 96506  97210     ** one option per row.
 96507  97211     */
 96508         -  if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
        97212  +  case PragTyp_COMPILE_OPTIONS: {
 96509  97213       int i = 0;
 96510  97214       const char *zOpt;
 96511  97215       sqlite3VdbeSetNumCols(v, 1);
 96512  97216       pParse->nMem = 1;
 96513  97217       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
 96514  97218       while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
 96515  97219         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
 96516  97220         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
 96517  97221       }
 96518         -  }else
        97222  +  }
        97223  +  break;
 96519  97224   #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
 96520  97225   
 96521  97226   #ifndef SQLITE_OMIT_WAL
 96522  97227     /*
 96523  97228     **   PRAGMA [database.]wal_checkpoint = passive|full|restart
 96524  97229     **
 96525  97230     ** Checkpoint the database.
 96526  97231     */
 96527         -  if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
        97232  +  case PragTyp_WAL_CHECKPOINT: {
 96528  97233       int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
 96529  97234       int eMode = SQLITE_CHECKPOINT_PASSIVE;
 96530  97235       if( zRight ){
 96531  97236         if( sqlite3StrICmp(zRight, "full")==0 ){
 96532  97237           eMode = SQLITE_CHECKPOINT_FULL;
 96533  97238         }else if( sqlite3StrICmp(zRight, "restart")==0 ){
 96534  97239           eMode = SQLITE_CHECKPOINT_RESTART;
 96535  97240         }
 96536  97241       }
 96537         -    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
 96538  97242       sqlite3VdbeSetNumCols(v, 3);
 96539  97243       pParse->nMem = 3;
 96540  97244       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
 96541  97245       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
 96542  97246       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
 96543  97247   
 96544  97248       sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
 96545  97249       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
 96546         -  }else
        97250  +  }
        97251  +  break;
 96547  97252   
 96548  97253     /*
 96549  97254     **   PRAGMA wal_autocheckpoint
 96550  97255     **   PRAGMA wal_autocheckpoint = N
 96551  97256     **
 96552  97257     ** Configure a database connection to automatically checkpoint a database
 96553  97258     ** after accumulating N frames in the log. Or query for the current value
 96554  97259     ** of N.
 96555  97260     */
 96556         -  if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
        97261  +  case PragTyp_WAL_AUTOCHECKPOINT: {
 96557  97262       if( zRight ){
 96558  97263         sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
 96559  97264       }
 96560  97265       returnSingleInt(pParse, "wal_autocheckpoint", 
 96561  97266          db->xWalCallback==sqlite3WalDefaultHook ? 
 96562  97267              SQLITE_PTR_TO_INT(db->pWalArg) : 0);
 96563         -  }else
        97268  +  }
        97269  +  break;
 96564  97270   #endif
 96565  97271   
 96566  97272     /*
 96567  97273     **  PRAGMA shrink_memory
 96568  97274     **
 96569  97275     ** This pragma attempts to free as much memory as possible from the
 96570  97276     ** current database connection.
 96571  97277     */
 96572         -  if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
        97278  +  case PragTyp_SHRINK_MEMORY: {
 96573  97279       sqlite3_db_release_memory(db);
 96574         -  }else
        97280  +    break;
        97281  +  }
 96575  97282   
 96576  97283     /*
 96577  97284     **   PRAGMA busy_timeout
 96578  97285     **   PRAGMA busy_timeout = N
 96579  97286     **
 96580  97287     ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
 96581  97288     ** if one is set.  If no busy handler or a different busy handler is set
 96582  97289     ** then 0 is returned.  Setting the busy_timeout to 0 or negative
 96583  97290     ** disables the timeout.
 96584  97291     */
 96585         -  if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
        97292  +  /*case PragTyp_BUSY_TIMEOUT*/ default: {
        97293  +    assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
 96586  97294       if( zRight ){
 96587  97295         sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
 96588  97296       }
 96589  97297       returnSingleInt(pParse, "timeout",  db->busyTimeout);
 96590         -  }else
        97298  +    break;
        97299  +  }
        97300  +
        97301  +  /*
        97302  +  **   PRAGMA soft_heap_limit
        97303  +  **   PRAGMA soft_heap_limit = N
        97304  +  **
        97305  +  ** Call sqlite3_soft_heap_limit64(N).  Return the result.  If N is omitted,
        97306  +  ** use -1.
        97307  +  */
        97308  +  case PragTyp_SOFT_HEAP_LIMIT: {
        97309  +    sqlite3_int64 N;
        97310  +    if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
        97311  +      sqlite3_soft_heap_limit64(N);
        97312  +    }
        97313  +    returnSingleInt(pParse, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
        97314  +    break;
        97315  +  }
 96591  97316   
 96592  97317   #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
 96593  97318     /*
 96594  97319     ** Report the current state of file logs for all databases
 96595  97320     */
 96596         -  if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
        97321  +  case PragTyp_LOCK_STATUS: {
 96597  97322       static const char *const azLockName[] = {
 96598  97323         "unlocked", "shared", "reserved", "pending", "exclusive"
 96599  97324       };
 96600  97325       int i;
 96601  97326       sqlite3VdbeSetNumCols(v, 2);
 96602  97327       pParse->nMem = 2;
 96603  97328       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
................................................................................
 96614  97339         }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
 96615  97340                                        SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
 96616  97341            zState = azLockName[j];
 96617  97342         }
 96618  97343         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
 96619  97344         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
 96620  97345       }
 96621         -
 96622         -  }else
        97346  +    break;
        97347  +  }
 96623  97348   #endif
 96624  97349   
 96625  97350   #ifdef SQLITE_HAS_CODEC
 96626         -  if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
 96627         -    sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
 96628         -  }else
 96629         -  if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
 96630         -    sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
 96631         -  }else
 96632         -  if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
 96633         -                 sqlite3StrICmp(zLeft, "hexrekey")==0) ){
 96634         -    int i, h1, h2;
 96635         -    char zKey[40];
 96636         -    for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
 96637         -      h1 += 9*(1&(h1>>6));
 96638         -      h2 += 9*(1&(h2>>6));
 96639         -      zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
 96640         -    }
 96641         -    if( (zLeft[3] & 0xf)==0xb ){
 96642         -      sqlite3_key_v2(db, zDb, zKey, i/2);
 96643         -    }else{
 96644         -      sqlite3_rekey_v2(db, zDb, zKey, i/2);
 96645         -    }
 96646         -  }else
        97351  +  case PragTyp_KEY: {
        97352  +    if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
        97353  +    break;
        97354  +  }
        97355  +  case PragTyp_REKEY: {
        97356  +    if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
        97357  +    break;
        97358  +  }
        97359  +  case PragTyp_HEXKEY: {
        97360  +    if( zRight ){
        97361  +      u8 iByte;
        97362  +      int i;
        97363  +      char zKey[40];
        97364  +      for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
        97365  +        iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
        97366  +        if( (i&1)!=0 ) zKey[i/2] = iByte;
        97367  +      }
        97368  +      if( (zLeft[3] & 0xf)==0xb ){
        97369  +        sqlite3_key_v2(db, zDb, zKey, i/2);
        97370  +      }else{
        97371  +        sqlite3_rekey_v2(db, zDb, zKey, i/2);
        97372  +      }
        97373  +    }
        97374  +    break;
        97375  +  }
 96647  97376   #endif
 96648  97377   #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
 96649         -  if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
        97378  +  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
 96650  97379   #ifdef SQLITE_HAS_CODEC
 96651  97380       if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
 96652  97381         sqlite3_activate_see(&zRight[4]);
 96653  97382       }
 96654  97383   #endif
 96655  97384   #ifdef SQLITE_ENABLE_CEROD
 96656  97385       if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
 96657  97386         sqlite3_activate_cerod(&zRight[6]);
 96658  97387       }
 96659  97388   #endif
 96660         -  }else
        97389  +  }
        97390  +  break;
 96661  97391   #endif
 96662  97392   
 96663         - 
 96664         -  {/* Empty ELSE clause */}
        97393  +  } /* End of the PRAGMA switch */
 96665  97394   
 96666  97395   pragma_out:
 96667  97396     sqlite3DbFree(db, zLeft);
 96668  97397     sqlite3DbFree(db, zRight);
 96669  97398   }
 96670  97399   
 96671  97400   #endif /* SQLITE_OMIT_PRAGMA */
................................................................................
 97808  98537   
 97809  98538     pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
 97810  98539     pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
 97811  98540   
 97812  98541     pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
 97813  98542     if( pEq && isOuterJoin ){
 97814  98543       ExprSetProperty(pEq, EP_FromJoin);
 97815         -    assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
 97816         -    ExprSetIrreducible(pEq);
        98544  +    assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
        98545  +    ExprSetVVAProperty(pEq, EP_NoReduce);
 97817  98546       pEq->iRightJoinTable = (i16)pE2->iTable;
 97818  98547     }
 97819  98548     *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
 97820  98549   }
 97821  98550   
 97822  98551   /*
 97823  98552   ** Set the EP_FromJoin property on all terms of the given expression.
................................................................................
 97844  98573   ** defer the handling of t1.x=5, it will be processed immediately
 97845  98574   ** after the t1 loop and rows with t1.x!=5 will never appear in
 97846  98575   ** the output, which is incorrect.
 97847  98576   */
 97848  98577   static void setJoinExpr(Expr *p, int iTable){
 97849  98578     while( p ){
 97850  98579       ExprSetProperty(p, EP_FromJoin);
 97851         -    assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
 97852         -    ExprSetIrreducible(p);
        98580  +    assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
        98581  +    ExprSetVVAProperty(p, EP_NoReduce);
 97853  98582       p->iRightJoinTable = (i16)iTable;
 97854  98583       setJoinExpr(p->pLeft, iTable);
 97855  98584       p = p->pRight;
 97856  98585     } 
 97857  98586   }
 97858  98587   
 97859  98588   /*
................................................................................
 98604  99333       sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
 98605  99334     }
 98606  99335   }
 98607  99336   
 98608  99337   /*
 98609  99338   ** Return a pointer to a string containing the 'declaration type' of the
 98610  99339   ** expression pExpr. The string may be treated as static by the caller.
        99340  +**
        99341  +** Also try to estimate the size of the returned value and return that
        99342  +** result in *pEstWidth.
 98611  99343   **
 98612  99344   ** The declaration type is the exact datatype definition extracted from the
 98613  99345   ** original CREATE TABLE statement if the expression is a column. The
 98614  99346   ** declaration type for a ROWID field is INTEGER. Exactly when an expression
 98615  99347   ** is considered a column can be complex in the presence of subqueries. The
 98616  99348   ** result-set expression in all of the following SELECT statements is 
 98617  99349   ** considered a column by this function.
................................................................................
 98618  99350   **
 98619  99351   **   SELECT col FROM tbl;
 98620  99352   **   SELECT (SELECT col FROM tbl;
 98621  99353   **   SELECT (SELECT col FROM tbl);
 98622  99354   **   SELECT abc FROM (SELECT col AS abc FROM tbl);
 98623  99355   ** 
 98624  99356   ** The declaration type for any expression other than a column is NULL.
        99357  +**
        99358  +** This routine has either 3 or 6 parameters depending on whether or not
        99359  +** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
 98625  99360   */
 98626         -static const char *columnType(
        99361  +#ifdef SQLITE_ENABLE_COLUMN_METADATA
        99362  +# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
        99363  +static const char *columnTypeImpl(
        99364  +  NameContext *pNC, 
        99365  +  Expr *pExpr,
        99366  +  const char **pzOrigDb,
        99367  +  const char **pzOrigTab,
        99368  +  const char **pzOrigCol,
        99369  +  u8 *pEstWidth
        99370  +){
        99371  +  char const *zOrigDb = 0;
        99372  +  char const *zOrigTab = 0;
        99373  +  char const *zOrigCol = 0;
        99374  +#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
        99375  +# define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
        99376  +static const char *columnTypeImpl(
 98627  99377     NameContext *pNC, 
 98628  99378     Expr *pExpr,
 98629         -  const char **pzOriginDb,
 98630         -  const char **pzOriginTab,
 98631         -  const char **pzOriginCol
        99379  +  u8 *pEstWidth
 98632  99380   ){
        99381  +#endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
 98633  99382     char const *zType = 0;
 98634         -  char const *zOriginDb = 0;
 98635         -  char const *zOriginTab = 0;
 98636         -  char const *zOriginCol = 0;
 98637  99383     int j;
        99384  +  u8 estWidth = 1;
        99385  +
 98638  99386     if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
 98639         -
 98640  99387     switch( pExpr->op ){
 98641  99388       case TK_AGG_COLUMN:
 98642  99389       case TK_COLUMN: {
 98643  99390         /* The expression is a column. Locate the table the column is being
 98644  99391         ** extracted from in NameContext.pSrcList. This table may be real
 98645  99392         ** database table or a subquery.
 98646  99393         */
................................................................................
 98693  99440             ** test case misc2.2.2) - it always evaluates to NULL.
 98694  99441             */
 98695  99442             NameContext sNC;
 98696  99443             Expr *p = pS->pEList->a[iCol].pExpr;
 98697  99444             sNC.pSrcList = pS->pSrc;
 98698  99445             sNC.pNext = pNC;
 98699  99446             sNC.pParse = pNC->pParse;
 98700         -          zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
        99447  +          zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); 
 98701  99448           }
 98702  99449         }else if( ALWAYS(pTab->pSchema) ){
 98703  99450           /* A real table */
 98704  99451           assert( !pS );
 98705  99452           if( iCol<0 ) iCol = pTab->iPKey;
 98706  99453           assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
        99454  +#ifdef SQLITE_ENABLE_COLUMN_METADATA
 98707  99455           if( iCol<0 ){
 98708  99456             zType = "INTEGER";
 98709         -          zOriginCol = "rowid";
        99457  +          zOrigCol = "rowid";
 98710  99458           }else{
 98711  99459             zType = pTab->aCol[iCol].zType;
 98712         -          zOriginCol = pTab->aCol[iCol].zName;
        99460  +          zOrigCol = pTab->aCol[iCol].zName;
        99461  +          estWidth = pTab->aCol[iCol].szEst;
 98713  99462           }
 98714         -        zOriginTab = pTab->zName;
        99463  +        zOrigTab = pTab->zName;
 98715  99464           if( pNC->pParse ){
 98716  99465             int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
 98717         -          zOriginDb = pNC->pParse->db->aDb[iDb].zName;
        99466  +          zOrigDb = pNC->pParse->db->aDb[iDb].zName;
 98718  99467           }
        99468  +#else
        99469  +        if( iCol<0 ){
        99470  +          zType = "INTEGER";
        99471  +        }else{
        99472  +          zType = pTab->aCol[iCol].zType;
        99473  +          estWidth = pTab->aCol[iCol].szEst;
        99474  +        }
        99475  +#endif
 98719  99476         }
 98720  99477         break;
 98721  99478       }
 98722  99479   #ifndef SQLITE_OMIT_SUBQUERY
 98723  99480       case TK_SELECT: {
 98724  99481         /* The expression is a sub-select. Return the declaration type and
 98725  99482         ** origin info for the single column in the result set of the SELECT
................................................................................
 98728  99485         NameContext sNC;
 98729  99486         Select *pS = pExpr->x.pSelect;
 98730  99487         Expr *p = pS->pEList->a[0].pExpr;
 98731  99488         assert( ExprHasProperty(pExpr, EP_xIsSelect) );
 98732  99489         sNC.pSrcList = pS->pSrc;
 98733  99490         sNC.pNext = pNC;
 98734  99491         sNC.pParse = pNC->pParse;
 98735         -      zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
        99492  +      zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); 
 98736  99493         break;
 98737  99494       }
 98738  99495   #endif
 98739  99496     }
 98740         -  
 98741         -  if( pzOriginDb ){
 98742         -    assert( pzOriginTab && pzOriginCol );
 98743         -    *pzOriginDb = zOriginDb;
 98744         -    *pzOriginTab = zOriginTab;
 98745         -    *pzOriginCol = zOriginCol;
        99497  +
        99498  +#ifdef SQLITE_ENABLE_COLUMN_METADATA  
        99499  +  if( pzOrigDb ){
        99500  +    assert( pzOrigTab && pzOrigCol );
        99501  +    *pzOrigDb = zOrigDb;
        99502  +    *pzOrigTab = zOrigTab;
        99503  +    *pzOrigCol = zOrigCol;
 98746  99504     }
        99505  +#endif
        99506  +  if( pEstWidth ) *pEstWidth = estWidth;
 98747  99507     return zType;
 98748  99508   }
 98749  99509   
 98750  99510   /*
 98751  99511   ** Generate code that will tell the VDBE the declaration types of columns
 98752  99512   ** in the result set.
 98753  99513   */
................................................................................
 98765  99525     for(i=0; i<pEList->nExpr; i++){
 98766  99526       Expr *p = pEList->a[i].pExpr;
 98767  99527       const char *zType;
 98768  99528   #ifdef SQLITE_ENABLE_COLUMN_METADATA
 98769  99529       const char *zOrigDb = 0;
 98770  99530       const char *zOrigTab = 0;
 98771  99531       const char *zOrigCol = 0;
 98772         -    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
        99532  +    zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
 98773  99533   
 98774  99534       /* The vdbe must make its own copy of the column-type and other 
 98775  99535       ** column specific strings, in case the schema is reset before this
 98776  99536       ** virtual machine is deleted.
 98777  99537       */
 98778  99538       sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
 98779  99539       sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
 98780  99540       sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
 98781  99541   #else
 98782         -    zType = columnType(&sNC, p, 0, 0, 0);
        99542  +    zType = columnType(&sNC, p, 0, 0, 0, 0);
 98783  99543   #endif
 98784  99544       sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
 98785  99545     }
 98786         -#endif /* SQLITE_OMIT_DECLTYPE */
        99546  +#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
 98787  99547   }
 98788  99548   
 98789  99549   /*
 98790  99550   ** Generate code that will tell the VDBE the names of columns
 98791  99551   ** in the result set.  This information is used to provide the
 98792  99552   ** azCol[] values in the callback.
 98793  99553   */
................................................................................
 98968  99728   ** routine goes through and adds the types and collations.
 98969  99729   **
 98970  99730   ** This routine requires that all identifiers in the SELECT
 98971  99731   ** statement be resolved.
 98972  99732   */
 98973  99733   static void selectAddColumnTypeAndCollation(
 98974  99734     Parse *pParse,        /* Parsing contexts */
 98975         -  int nCol,             /* Number of columns */
 98976         -  Column *aCol,         /* List of columns */
        99735  +  Table *pTab,          /* Add column type information to this table */
 98977  99736     Select *pSelect       /* SELECT used to determine types and collations */
 98978  99737   ){
 98979  99738     sqlite3 *db = pParse->db;
 98980  99739     NameContext sNC;
 98981  99740     Column *pCol;
 98982  99741     CollSeq *pColl;
 98983  99742     int i;
 98984  99743     Expr *p;
 98985  99744     struct ExprList_item *a;
        99745  +  u64 szAll = 0;
 98986  99746   
 98987  99747     assert( pSelect!=0 );
 98988  99748     assert( (pSelect->selFlags & SF_Resolved)!=0 );
 98989         -  assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
        99749  +  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
 98990  99750     if( db->mallocFailed ) return;
 98991  99751     memset(&sNC, 0, sizeof(sNC));
 98992  99752     sNC.pSrcList = pSelect->pSrc;
 98993  99753     a = pSelect->pEList->a;
 98994         -  for(i=0, pCol=aCol; i<nCol; i++, pCol++){
        99754  +  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
 98995  99755       p = a[i].pExpr;
 98996         -    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
        99756  +    pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
        99757  +    szAll += pCol->szEst;
 98997  99758       pCol->affinity = sqlite3ExprAffinity(p);
 98998  99759       if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
 98999  99760       pColl = sqlite3ExprCollSeq(pParse, p);
 99000  99761       if( pColl ){
 99001  99762         pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
 99002  99763       }
 99003  99764     }
        99765  +  pTab->szTabRow = sqlite3LogEst(szAll*4);
 99004  99766   }
 99005  99767   
 99006  99768   /*
 99007  99769   ** Given a SELECT statement, generate a Table structure that describes
 99008  99770   ** the result set of that SELECT.
 99009  99771   */
 99010  99772   SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
................................................................................
 99024  99786       return 0;
 99025  99787     }
 99026  99788     /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
 99027  99789     ** is disabled */
 99028  99790     assert( db->lookaside.bEnabled==0 );
 99029  99791     pTab->nRef = 1;
 99030  99792     pTab->zName = 0;
 99031         -  pTab->nRowEst = 1000000;
        99793  +  pTab->nRowEst = 1048576;
 99032  99794     selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
 99033         -  selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
        99795  +  selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
 99034  99796     pTab->iPKey = -1;
 99035  99797     if( db->mallocFailed ){
 99036  99798       sqlite3DeleteTable(db, pTab);
 99037  99799       return 0;
 99038  99800     }
 99039  99801     return pTab;
 99040  99802   }
................................................................................
100938 101700         /* A sub-query in the FROM clause of a SELECT */
100939 101701         assert( pSel!=0 );
100940 101702         assert( pFrom->pTab==0 );
100941 101703         sqlite3WalkSelect(pWalker, pSel);
100942 101704         pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
100943 101705         if( pTab==0 ) return WRC_Abort;
100944 101706         pTab->nRef = 1;
100945         -      pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
       101707  +      pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
100946 101708         while( pSel->pPrior ){ pSel = pSel->pPrior; }
100947 101709         selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
100948 101710         pTab->iPKey = -1;
100949         -      pTab->nRowEst = 1000000;
       101711  +      pTab->nRowEst = 1048576;
100950 101712         pTab->tabFlags |= TF_Ephemeral;
100951 101713   #endif
100952 101714       }else{
100953 101715         /* An ordinary table or view name in the FROM clause */
100954 101716         assert( pFrom->pTab==0 );
100955 101717         pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
100956 101718         if( pTab==0 ) return WRC_Abort;
................................................................................
101226 101988       for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
101227 101989         Table *pTab = pFrom->pTab;
101228 101990         if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
101229 101991           /* A sub-query in the FROM clause of a SELECT */
101230 101992           Select *pSel = pFrom->pSelect;
101231 101993           assert( pSel );
101232 101994           while( pSel->pPrior ) pSel = pSel->pPrior;
101233         -        selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
       101995  +        selectAddColumnTypeAndCollation(pParse, pTab, pSel);
101234 101996         }
101235 101997       }
101236 101998     }
101237 101999     return WRC_Continue;
101238 102000   }
101239 102001   #endif
101240 102002   
................................................................................
102141 102903           KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
102142 102904           Index *pBest = 0;                    /* Best index found so far */
102143 102905           int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
102144 102906   
102145 102907           sqlite3CodeVerifySchema(pParse, iDb);
102146 102908           sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
102147 102909   
102148         -        /* Search for the index that has the least amount of columns. If
102149         -        ** there is such an index, and it has less columns than the table
102150         -        ** does, then we can assume that it consumes less space on disk and
102151         -        ** will therefore be cheaper to scan to determine the query result.
102152         -        ** In this case set iRoot to the root page number of the index b-tree
102153         -        ** and pKeyInfo to the KeyInfo structure required to navigate the
102154         -        ** index.
       102910  +        /* Search for the index that has the lowest scan cost.
102155 102911           **
102156 102912           ** (2011-04-15) Do not do a full scan of an unordered index.
       102913  +        **
       102914  +        ** (2013-10-03) Do not count the entires in a partial index.
102157 102915           **
102158 102916           ** In practice the KeyInfo structure will not be used. It is only 
102159 102917           ** passed to keep OP_OpenRead happy.
102160 102918           */
102161 102919           for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102162         -          if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
       102920  +          if( pIdx->bUnordered==0
       102921  +           && pIdx->szIdxRow<pTab->szTabRow
       102922  +           && pIdx->pPartIdxWhere==0
       102923  +           && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
       102924  +          ){
102163 102925               pBest = pIdx;
102164 102926             }
102165 102927           }
102166         -        if( pBest && pBest->nColumn<pTab->nCol ){
       102928  +        if( pBest ){
102167 102929             iRoot = pBest->tnum;
102168 102930             pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
102169 102931           }
102170 102932   
102171 102933           /* Open a read-only cursor, execute the OP_Count, close the cursor. */
102172 102934           sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
102173 102935           if( pKeyInfo ){
................................................................................
102737 103499           && pTab->pSchema==db->aDb[1].pSchema ){
102738 103500       iDb = 1;
102739 103501     }
102740 103502   
102741 103503     /* Ensure the table name matches database name and that the table exists */
102742 103504     if( db->mallocFailed ) goto trigger_cleanup;
102743 103505     assert( pTableName->nSrc==1 );
102744         -  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
102745         -      sqlite3FixSrcList(&sFix, pTableName) ){
       103506  +  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
       103507  +  if( sqlite3FixSrcList(&sFix, pTableName) ){
102746 103508       goto trigger_cleanup;
102747 103509     }
102748 103510     pTab = sqlite3SrcListLookup(pParse, pTableName);
102749 103511     if( !pTab ){
102750 103512       /* The table does not exist. */
102751 103513       if( db->init.iDb==1 ){
102752 103514         /* Ticket #3810.
................................................................................
102880 103642     pTrig->step_list = pStepList;
102881 103643     while( pStepList ){
102882 103644       pStepList->pTrig = pTrig;
102883 103645       pStepList = pStepList->pNext;
102884 103646     }
102885 103647     nameToken.z = pTrig->zName;
102886 103648     nameToken.n = sqlite3Strlen30(nameToken.z);
102887         -  if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
102888         -          && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
       103649  +  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
       103650  +  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) 
       103651  +   || sqlite3FixExpr(&sFix, pTrig->pWhen) 
       103652  +  ){
102889 103653       goto triggerfinish_cleanup;
102890 103654     }
102891 103655   
102892 103656     /* if we are not initializing,
102893 103657     ** build the sqlite_master entry
102894 103658     */
102895 103659     if( !db->init.busy ){
................................................................................
104472 105236       }
104473 105237     }
104474 105238   
104475 105239     return vacuumFinalize(db, pStmt, pzErrMsg);
104476 105240   }
104477 105241   
104478 105242   /*
104479         -** The non-standard VACUUM command is used to clean up the database,
       105243  +** The VACUUM command is used to clean up the database,
104480 105244   ** collapse free space, etc.  It is modelled after the VACUUM command
104481         -** in PostgreSQL.
       105245  +** in PostgreSQL.  The VACUUM command works as follows:
104482 105246   **
104483         -** In version 1.0.x of SQLite, the VACUUM command would call
104484         -** gdbm_reorganize() on all the database tables.  But beginning
104485         -** with 2.0.0, SQLite no longer uses GDBM so this command has
104486         -** become a no-op.
       105247  +**   (1)  Create a new transient database file
       105248  +**   (2)  Copy all content from the database being vacuumed into
       105249  +**        the new transient database file
       105250  +**   (3)  Copy content from the transient database back into the
       105251  +**        original database.
       105252  +**
       105253  +** The transient database requires temporary disk space approximately
       105254  +** equal to the size of the original database.  The copy operation of
       105255  +** step (3) requires additional temporary disk space approximately equal
       105256  +** to the size of the original database for the rollback journal.
       105257  +** Hence, temporary disk space that is approximately 2x the size of the
       105258  +** orginal database is required.  Every page of the database is written
       105259  +** approximately 3 times:  Once for step (2) and twice for step (3).
       105260  +** Two writes per page are required in step (3) because the original
       105261  +** database content must be written into the rollback journal prior to
       105262  +** overwriting the database with the vacuumed content.
       105263  +**
       105264  +** Only 1x temporary space and only 1x writes would be required if
       105265  +** the copy of step (3) were replace by deleting the original database
       105266  +** and renaming the transient database as the original.  But that will
       105267  +** not work if other processes are attached to the original database.
       105268  +** And a power loss in between deleting the original and renaming the
       105269  +** transient would cause the database file to appear to be deleted
       105270  +** following reboot.
104487 105271   */
104488 105272   SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
104489 105273     Vdbe *v = sqlite3GetVdbe(pParse);
104490 105274     if( v ){
104491 105275       sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
104492 105276       sqlite3VdbeUsesBtree(v, 0);
104493 105277     }
................................................................................
105897 106681   typedef struct WherePath WherePath;
105898 106682   typedef struct WhereTerm WhereTerm;
105899 106683   typedef struct WhereLoopBuilder WhereLoopBuilder;
105900 106684   typedef struct WhereScan WhereScan;
105901 106685   typedef struct WhereOrCost WhereOrCost;
105902 106686   typedef struct WhereOrSet WhereOrSet;
105903 106687   
105904         -/*
105905         -** Cost X is tracked as 10*log2(X) stored in a 16-bit integer.  The
105906         -** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
105907         -** (Virtual tables can return a larger cost, but let's assume they do not.)
105908         -** So all costs can be stored in a 16-bit unsigned integer without risk
105909         -** of overflow.
105910         -**
105911         -** Costs are estimates, so no effort is made to compute 10*log2(X) exactly.
105912         -** Instead, a close estimate is used.  Any value of X<=1 is stored as 0.
105913         -** X=2 is 10.  X=3 is 16.  X=1000 is 99. etc.
105914         -**
105915         -** The tool/wherecosttest.c source file implements a command-line program
105916         -** that will convert WhereCosts to integers, convert integers to WhereCosts
105917         -** and do addition and multiplication on WhereCost values.  The wherecosttest
105918         -** command-line program is a useful utility to have around when working with
105919         -** this module.
105920         -*/
105921         -typedef unsigned short int WhereCost;
105922         -
105923 106688   /*
105924 106689   ** This object contains information needed to implement a single nested
105925 106690   ** loop in WHERE clause.
105926 106691   **
105927 106692   ** Contrast this object with WhereLoop.  This object describes the
105928 106693   ** implementation of the loop.  WhereLoop describes the algorithm.
105929 106694   ** This object contains a pointer to the WhereLoop algorithm as one of
................................................................................
105980 106745     Bitmask prereq;       /* Bitmask of other loops that must run first */
105981 106746     Bitmask maskSelf;     /* Bitmask identifying table iTab */
105982 106747   #ifdef SQLITE_DEBUG
105983 106748     char cId;             /* Symbolic ID of this loop for debugging use */
105984 106749   #endif
105985 106750     u8 iTab;              /* Position in FROM clause of table for this loop */
105986 106751     u8 iSortIdx;          /* Sorting index number.  0==None */
105987         -  WhereCost rSetup;     /* One-time setup cost (ex: create transient index) */
105988         -  WhereCost rRun;       /* Cost of running each loop */
105989         -  WhereCost nOut;       /* Estimated number of output rows */
       106752  +  LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
       106753  +  LogEst rRun;          /* Cost of running each loop */
       106754  +  LogEst nOut;          /* Estimated number of output rows */
105990 106755     union {
105991 106756       struct {               /* Information for internal btree tables */
105992 106757         int nEq;               /* Number of equality constraints */
105993 106758         Index *pIndex;         /* Index used, or NULL */
105994 106759       } btree;
105995 106760       struct {               /* Information for virtual tables */
105996 106761         int idxNum;            /* Index number */
................................................................................
106012 106777   
106013 106778   /* This object holds the prerequisites and the cost of running a
106014 106779   ** subquery on one operand of an OR operator in the WHERE clause.
106015 106780   ** See WhereOrSet for additional information 
106016 106781   */
106017 106782   struct WhereOrCost {
106018 106783     Bitmask prereq;     /* Prerequisites */
106019         -  WhereCost rRun;     /* Cost of running this subquery */
106020         -  WhereCost nOut;     /* Number of outputs for this subquery */
       106784  +  LogEst rRun;        /* Cost of running this subquery */
       106785  +  LogEst nOut;        /* Number of outputs for this subquery */
106021 106786   };
106022 106787   
106023 106788   /* The WhereOrSet object holds a set of possible WhereOrCosts that
106024 106789   ** correspond to the subquery(s) of OR-clause processing.  Only the
106025 106790   ** best N_OR_COST elements are retained.
106026 106791   */
106027 106792   #define N_OR_COST 3
................................................................................
106051 106816   ** of length 2.  And so forth until the length of WherePaths equals the
106052 106817   ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
106053 106818   ** at the end is the choosen query plan.
106054 106819   */
106055 106820   struct WherePath {
106056 106821     Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
106057 106822     Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
106058         -  WhereCost nRow;       /* Estimated number of rows generated by this path */
106059         -  WhereCost rCost;      /* Total cost of this path */
       106823  +  LogEst nRow;          /* Estimated number of rows generated by this path */
       106824  +  LogEst rCost;         /* Total cost of this path */
106060 106825     u8 isOrdered;         /* True if this path satisfies ORDER BY */
106061 106826     u8 isOrderedValid;    /* True if the isOrdered field is valid */
106062 106827     WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
106063 106828   };
106064 106829   
106065 106830   /*
106066 106831   ** The query generator uses an array of instances of this structure to
................................................................................
106118 106883     int iParent;            /* Disable pWC->a[iParent] when this term disabled */
106119 106884     int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
106120 106885     union {
106121 106886       int leftColumn;         /* Column number of X in "X <op> <expr>" */
106122 106887       WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
106123 106888       WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
106124 106889     } u;
       106890  +  LogEst truthProb;       /* Probability of truth for this expression */
106125 106891     u16 eOperator;          /* A WO_xx value describing <op> */
106126 106892     u8 wtFlags;             /* TERM_xxx bit flags.  See below */
106127 106893     u8 nChild;              /* Number of children that must disable us */
106128 106894     WhereClause *pWC;       /* The clause this term is part of */
106129 106895     Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
106130 106896     Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
106131 106897   };
................................................................................
106265 107031   struct WhereInfo {
106266 107032     Parse *pParse;            /* Parsing and code generating context */
106267 107033     SrcList *pTabList;        /* List of tables in the join */
106268 107034     ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
106269 107035     ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
106270 107036     WhereLoop *pLoops;        /* List of all WhereLoop objects */
106271 107037     Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
106272         -  WhereCost nRowOut;        /* Estimated number of output rows */
       107038  +  LogEst nRowOut;           /* Estimated number of output rows */
106273 107039     u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
106274 107040     u8 bOBSat;                /* ORDER BY satisfied by indices */
106275 107041     u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
106276 107042     u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
106277 107043     u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
106278 107044     u8 nLevel;                /* Number of nested loop */
106279 107045     int iTop;                 /* The very beginning of the WHERE loop */
................................................................................
106325 107091   #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
106326 107092   #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
106327 107093   #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
106328 107094   #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
106329 107095   #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
106330 107096   #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
106331 107097   
106332         -
106333         -/* Convert a WhereCost value (10 times log2(X)) into its integer value X.
106334         -** A rough approximation is used.  The value returned is not exact.
106335         -*/
106336         -static u64 whereCostToInt(WhereCost x){
106337         -  u64 n;
106338         -  if( x<10 ) return 1;
106339         -  n = x%10;
106340         -  x /= 10;
106341         -  if( n>=5 ) n -= 2;
106342         -  else if( n>=1 ) n -= 1;
106343         -  if( x>=3 ) return (n+8)<<(x-3);
106344         -  return (n+8)>>(3-x);
106345         -}
106346         -
106347 107098   /*
106348 107099   ** Return the estimated number of output rows from a WHERE clause
106349 107100   */
106350 107101   SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
106351         -  return whereCostToInt(pWInfo->nRowOut);
       107102  +  return sqlite3LogEstToInt(pWInfo->nRowOut);
106352 107103   }
106353 107104   
106354 107105   /*
106355 107106   ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
106356 107107   ** WHERE clause returns outputs for DISTINCT processing.
106357 107108   */
106358 107109   SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
................................................................................
106406 107157   ** The new entry might overwrite an existing entry, or it might be
106407 107158   ** appended, or it might be discarded.  Do whatever is the right thing
106408 107159   ** so that pSet keeps the N_OR_COST best entries seen so far.
106409 107160   */
106410 107161   static int whereOrInsert(
106411 107162     WhereOrSet *pSet,      /* The WhereOrSet to be updated */
106412 107163     Bitmask prereq,        /* Prerequisites of the new entry */
106413         -  WhereCost rRun,        /* Run-cost of the new entry */
106414         -  WhereCost nOut         /* Number of outputs for the new entry */
       107164  +  LogEst rRun,           /* Run-cost of the new entry */
       107165  +  LogEst nOut            /* Number of outputs for the new entry */
106415 107166   ){
106416 107167     u16 i;
106417 107168     WhereOrCost *p;
106418 107169     for(i=pSet->n, p=pSet->a; i>0; i--, p++){
106419 107170       if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
106420 107171         goto whereOrInsert_done;
106421 107172       }
................................................................................
106533 107284       memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
106534 107285       if( pOld!=pWC->aStatic ){
106535 107286         sqlite3DbFree(db, pOld);
106536 107287       }
106537 107288       pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
106538 107289     }
106539 107290     pTerm = &pWC->a[idx = pWC->nTerm++];
       107291  +  if( p && ExprHasProperty(p, EP_Unlikely) ){
       107292  +    pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
       107293  +  }else{
       107294  +    pTerm->truthProb = -1;
       107295  +  }
106540 107296     pTerm->pExpr = sqlite3ExprSkipCollate(p);
106541 107297     pTerm->wtFlags = wtFlags;
106542 107298     pTerm->pWC = pWC;
106543 107299     pTerm->iParent = -1;
106544 107300     return idx;
106545 107301   }
106546 107302   
................................................................................
107793 108549         return 1;
107794 108550       }
107795 108551     }
107796 108552   
107797 108553     return 0;
107798 108554   }
107799 108555   
107800         -/* 
107801         -** Find (an approximate) sum of two WhereCosts.  This computation is
107802         -** not a simple "+" operator because WhereCost is stored as a logarithmic
107803         -** value.
107804         -** 
107805         -*/
107806         -static WhereCost whereCostAdd(WhereCost a, WhereCost b){
107807         -  static const unsigned char x[] = {
107808         -     10, 10,                         /* 0,1 */
107809         -      9, 9,                          /* 2,3 */
107810         -      8, 8,                          /* 4,5 */
107811         -      7, 7, 7,                       /* 6,7,8 */
107812         -      6, 6, 6,                       /* 9,10,11 */
107813         -      5, 5, 5,                       /* 12-14 */
107814         -      4, 4, 4, 4,                    /* 15-18 */
107815         -      3, 3, 3, 3, 3, 3,              /* 19-24 */
107816         -      2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
107817         -  };
107818         -  if( a>=b ){
107819         -    if( a>b+49 ) return a;
107820         -    if( a>b+31 ) return a+1;
107821         -    return a+x[a-b];
107822         -  }else{
107823         -    if( b>a+49 ) return b;
107824         -    if( b>a+31 ) return b+1;
107825         -    return b+x[b-a];
107826         -  }
107827         -}
107828         -
107829         -/*
107830         -** Convert an integer into a WhereCost.  In other words, compute a
107831         -** good approximatation for 10*log2(x).
107832         -*/
107833         -static WhereCost whereCost(tRowcnt x){
107834         -  static WhereCost a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
107835         -  WhereCost y = 40;
107836         -  if( x<8 ){
107837         -    if( x<2 ) return 0;
107838         -    while( x<8 ){  y -= 10; x <<= 1; }
107839         -  }else{
107840         -    while( x>255 ){ y += 40; x >>= 4; }
107841         -    while( x>15 ){  y += 10; x >>= 1; }
107842         -  }
107843         -  return a[x&7] + y - 10;
107844         -}
107845         -
107846         -#ifndef SQLITE_OMIT_VIRTUALTABLE
107847         -/*
107848         -** Convert a double (as received from xBestIndex of a virtual table)
107849         -** into a WhereCost.  In other words, compute an approximation for
107850         -** 10*log2(x).
107851         -*/
107852         -static WhereCost whereCostFromDouble(double x){
107853         -  u64 a;
107854         -  WhereCost e;
107855         -  assert( sizeof(x)==8 && sizeof(a)==8 );
107856         -  if( x<=1 ) return 0;
107857         -  if( x<=2000000000 ) return whereCost((tRowcnt)x);
107858         -  memcpy(&a, &x, 8);
107859         -  e = (a>>52) - 1022;
107860         -  return e*10;
107861         -}
107862         -#endif /* SQLITE_OMIT_VIRTUALTABLE */
107863 108556   
107864 108557   /*
107865 108558   ** Estimate the logarithm of the input value to base 2.
107866 108559   */
107867         -static WhereCost estLog(WhereCost N){
107868         -  WhereCost x = whereCost(N);
       108560  +static LogEst estLog(LogEst N){
       108561  +  LogEst x = sqlite3LogEst(N);
107869 108562     return x>33 ? x - 33 : 0;
107870 108563   }
107871 108564   
107872 108565   /*
107873 108566   ** Two routines for printing the content of an sqlite3_index_info
107874 108567   ** structure.  Used for testing and debugging only.  If neither
107875 108568   ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
................................................................................
108277 108970     IndexSample *aSample = pIdx->aSample;
108278 108971     int iCol;                   /* Index of required stats in anEq[] etc. */
108279 108972     int iMin = 0;               /* Smallest sample not yet tested */
108280 108973     int i = pIdx->nSample;      /* Smallest sample larger than or equal to pRec */
108281 108974     int iTest;                  /* Next sample to test */
108282 108975     int res;                    /* Result of comparison operation */
108283 108976   
       108977  +#ifndef SQLITE_DEBUG
       108978  +  UNUSED_PARAMETER( pParse );
       108979  +#endif
108284 108980     assert( pRec!=0 || pParse->db->mallocFailed );
108285 108981     if( pRec==0 ) return;
108286 108982     iCol = pRec->nField - 1;
108287 108983     assert( pIdx->nSample>0 );
108288 108984     assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
108289 108985     do{
108290 108986       iTest = (iMin+i)/2;
................................................................................
108374 109070   ** then nEq is set to 1 (as the range restricted column, b, is the second 
108375 109071   ** left-most column of the index). Or, if the query is:
108376 109072   **
108377 109073   **   ... FROM t1 WHERE a > ? AND a < ? ...
108378 109074   **
108379 109075   ** then nEq is set to 0.
108380 109076   **
108381         -** When this function is called, *pnOut is set to the whereCost() of the
       109077  +** When this function is called, *pnOut is set to the sqlite3LogEst() of the
108382 109078   ** number of rows that the index scan is expected to visit without 
108383 109079   ** considering the range constraints. If nEq is 0, this is the number of 
108384 109080   ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
108385 109081   ** to account for the range contraints pLower and pUpper.
108386 109082   ** 
108387 109083   ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
108388 109084   ** used, each range inequality reduces the search space by a factor of 4. 
................................................................................
108390 109086   ** rows visited by a factor of 16.
108391 109087   */
108392 109088   static int whereRangeScanEst(
108393 109089     Parse *pParse,       /* Parsing & code generating context */
108394 109090     WhereLoopBuilder *pBuilder,
108395 109091     WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
108396 109092     WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
108397         -  WhereCost *pnOut     /* IN/OUT: Number of rows visited */
       109093  +  WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
108398 109094   ){
108399 109095     int rc = SQLITE_OK;
108400         -  int nOut = (int)*pnOut;
       109096  +  int nOut = pLoop->nOut;
       109097  +  LogEst nNew;
108401 109098   
108402 109099   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
108403         -  Index *p = pBuilder->pNew->u.btree.pIndex;
108404         -  int nEq = pBuilder->pNew->u.btree.nEq;
       109100  +  Index *p = pLoop->u.btree.pIndex;
       109101  +  int nEq = pLoop->u.btree.nEq;
108405 109102   
108406 109103     if( p->nSample>0
108407 109104      && nEq==pBuilder->nRecValid
108408 109105      && nEq<p->nSampleCol
108409 109106      && OptimizationEnabled(pParse->db, SQLITE_Stat3) 
108410 109107     ){
108411 109108       UnpackedRecord *pRec = pBuilder->pRec;
................................................................................
108456 109153         assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
108457 109154         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
108458 109155         if( rc==SQLITE_OK && bOk ){
108459 109156           tRowcnt iNew;
108460 109157           whereKeyStats(pParse, p, pRec, 0, a);
108461 109158           iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
108462 109159           if( iNew>iLower ) iLower = iNew;
       109160  +        nOut--;
108463 109161         }
108464 109162       }
108465 109163   
108466 109164       /* If possible, improve on the iUpper estimate using ($P:$U). */
108467 109165       if( pUpper ){
108468 109166         int bOk;                    /* True if value is extracted from pExpr */
108469 109167         Expr *pExpr = pUpper->pExpr->pRight;
................................................................................
108470 109168         assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
108471 109169         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
108472 109170         if( rc==SQLITE_OK && bOk ){
108473 109171           tRowcnt iNew;
108474 109172           whereKeyStats(pParse, p, pRec, 1, a);
108475 109173           iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
108476 109174           if( iNew<iUpper ) iUpper = iNew;
       109175  +        nOut--;
108477 109176         }
108478 109177       }
108479 109178   
108480 109179       pBuilder->pRec = pRec;
108481 109180       if( rc==SQLITE_OK ){
108482         -      WhereCost nNew;
108483 109181         if( iUpper>iLower ){
108484         -        nNew = whereCost(iUpper - iLower);
       109182  +        nNew = sqlite3LogEst(iUpper - iLower);
108485 109183         }else{
108486         -        nNew = 10;        assert( 10==whereCost(2) );
       109184  +        nNew = 10;        assert( 10==sqlite3LogEst(2) );
108487 109185         }
108488 109186         if( nNew<nOut ){
108489 109187           nOut = nNew;
108490 109188         }
108491         -      *pnOut = (WhereCost)nOut;
       109189  +      pLoop->nOut = (LogEst)nOut;
108492 109190         WHERETRACE(0x100, ("range scan regions: %u..%u  est=%d\n",
108493 109191                            (u32)iLower, (u32)iUpper, nOut));
108494 109192         return SQLITE_OK;
108495 109193       }
108496 109194     }
108497 109195   #else
108498 109196     UNUSED_PARAMETER(pParse);
108499 109197     UNUSED_PARAMETER(pBuilder);
108500 109198   #endif
108501 109199     assert( pLower || pUpper );
108502 109200     /* TUNING:  Each inequality constraint reduces the search space 4-fold.
108503 109201     ** A BETWEEN operator, therefore, reduces the search space 16-fold */
       109202  +  nNew = nOut;
108504 109203     if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
108505         -    nOut -= 20;        assert( 20==whereCost(4) );
       109204  +    nNew -= 20;        assert( 20==sqlite3LogEst(4) );
       109205  +    nOut--;
108506 109206     }
108507 109207     if( pUpper ){
108508         -    nOut -= 20;        assert( 20==whereCost(4) );
       109208  +    nNew -= 20;        assert( 20==sqlite3LogEst(4) );
       109209  +    nOut--;
108509 109210     }
108510         -  if( nOut<10 ) nOut = 10;
108511         -  *pnOut = (WhereCost)nOut;
       109211  +  if( nNew<10 ) nNew = 10;
       109212  +  if( nNew<nOut ) nOut = nNew;
       109213  +  pLoop->nOut = (LogEst)nOut;
108512 109214     return rc;
108513 109215   }
108514 109216   
108515 109217   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
108516 109218   /*
108517 109219   ** Estimate the number of rows that will be returned based on
108518 109220   ** an equality constraint x=VALUE and where that VALUE occurs in
................................................................................
110038 110740       ){
110039 110741         /* This branch taken when p is equal or better than pTemplate in 
110040 110742         ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
110041 110743         ** (4) number of output rows. */
110042 110744         assert( p->rSetup==pTemplate->rSetup );
110043 110745         if( p->prereq==pTemplate->prereq
110044 110746          && p->nLTerm<pTemplate->nLTerm
110045         -       && (p->wsFlags & WHERE_INDEXED)!=0
110046         -       && (pTemplate->wsFlags & WHERE_INDEXED)!=0
110047         -       && p->u.btree.pIndex==pTemplate->u.btree.pIndex
       110747  +       && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
       110748  +       && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
       110749  +          || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
110048 110750         ){
110049 110751           /* Overwrite an existing WhereLoop with an similar one that uses
110050 110752           ** more terms of the index */
110051 110753           pNext = p->pNextLoop;
110052 110754           break;
110053 110755         }else{
110054 110756           /* pTemplate is not helpful.
................................................................................
110055 110757           ** Return without changing or adding anything */
110056 110758           goto whereLoopInsert_noop;
110057 110759         }
110058 110760       }
110059 110761       if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
110060 110762        && p->rRun>=pTemplate->rRun
110061 110763        && p->nOut>=pTemplate->nOut
110062         -     && ALWAYS(p->rSetup>=pTemplate->rSetup) /* See SETUP-INVARIANT above */
110063 110764       ){
110064 110765         /* Overwrite an existing WhereLoop with a better one: one that is
110065 110766         ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
110066 110767         ** or (4) number of output rows, and is no worse in any of those
110067 110768         ** categories. */
       110769  +      assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
110068 110770         pNext = p->pNextLoop;
110069 110771         break;
110070 110772       }
110071 110773     }
110072 110774   
110073 110775     /* If we reach this point it means that either p[] should be overwritten
110074 110776     ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
................................................................................
110106 110808     if( sqlite3WhereTrace & 0x8 ){
110107 110809       sqlite3DebugPrintf("ins-noop: ");
110108 110810       whereLoopPrint(pTemplate, pWInfo->pTabList);
110109 110811     }
110110 110812   #endif
110111 110813     return SQLITE_OK;  
110112 110814   }
       110815  +
       110816  +/*
       110817  +** Adjust the WhereLoop.nOut value downward to account for terms of the
       110818  +** WHERE clause that reference the loop but which are not used by an
       110819  +** index.
       110820  +**
       110821  +** In the current implementation, the first extra WHERE clause term reduces
       110822  +** the number of output rows by a factor of 10 and each additional term
       110823  +** reduces the number of output rows by sqrt(2).
       110824  +*/
       110825  +static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
       110826  +  WhereTerm *pTerm, *pX;
       110827  +  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
       110828  +  int i, j;
       110829  +
       110830  +  if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
       110831  +    return;
       110832  +  }
       110833  +  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
       110834  +    if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
       110835  +    if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
       110836  +    if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
       110837  +    for(j=pLoop->nLTerm-1; j>=0; j--){
       110838  +      pX = pLoop->aLTerm[j];
       110839  +      if( pX==pTerm ) break;
       110840  +      if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
       110841  +    }
       110842  +    if( j<0 ) pLoop->nOut += pTerm->truthProb;
       110843  +  }
       110844  +}
110113 110845   
110114 110846   /*
110115 110847   ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
110116 110848   ** Try to match one more.
110117 110849   **
110118 110850   ** If pProbe->tnum==0, that means pIndex is a fake index used for the
110119 110851   ** INTEGER PRIMARY KEY.
110120 110852   */
110121 110853   static int whereLoopAddBtreeIndex(
110122 110854     WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
110123 110855     struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
110124 110856     Index *pProbe,                  /* An index on pSrc */
110125         -  WhereCost nInMul                /* log(Number of iterations due to IN) */
       110857  +  LogEst nInMul                   /* log(Number of iterations due to IN) */
110126 110858   ){
110127 110859     WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
110128 110860     Parse *pParse = pWInfo->pParse;        /* Parsing context */
110129 110861     sqlite3 *db = pParse->db;       /* Database connection malloc context */
110130 110862     WhereLoop *pNew;                /* Template WhereLoop under construction */
110131 110863     WhereTerm *pTerm;               /* A WhereTerm under consideration */
110132 110864     int opMask;                     /* Valid operators for constraints */
110133 110865     WhereScan scan;                 /* Iterator for WHERE terms */
110134 110866     Bitmask saved_prereq;           /* Original value of pNew->prereq */
110135 110867     u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
110136 110868     int saved_nEq;                  /* Original value of pNew->u.btree.nEq */
110137 110869     u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
110138         -  WhereCost saved_nOut;           /* Original value of pNew->nOut */
       110870  +  LogEst saved_nOut;              /* Original value of pNew->nOut */
110139 110871     int iCol;                       /* Index of the column in the table */
110140 110872     int rc = SQLITE_OK;             /* Return code */
110141         -  WhereCost nRowEst;              /* Estimated index selectivity */
110142         -  WhereCost rLogSize;             /* Logarithm of table size */
       110873  +  LogEst nRowEst;                 /* Estimated index selectivity */
       110874  +  LogEst rLogSize;                /* Logarithm of table size */
110143 110875     WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
110144 110876   
110145 110877     pNew = pBuilder->pNew;
110146 110878     if( db->mallocFailed ) return SQLITE_NOMEM;
110147 110879   
110148 110880     assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
110149 110881     assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
................................................................................
110155 110887       opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
110156 110888     }
110157 110889     if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
110158 110890   
110159 110891     assert( pNew->u.btree.nEq<=pProbe->nColumn );
110160 110892     if( pNew->u.btree.nEq < pProbe->nColumn ){
110161 110893       iCol = pProbe->aiColumn[pNew->u.btree.nEq];
110162         -    nRowEst = whereCost(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
       110894  +    nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
110163 110895       if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
110164 110896     }else{
110165 110897       iCol = -1;
110166 110898       nRowEst = 0;
110167 110899     }
110168 110900     pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
110169 110901                           opMask, pProbe);
110170 110902     saved_nEq = pNew->u.btree.nEq;
110171 110903     saved_nLTerm = pNew->nLTerm;
110172 110904     saved_wsFlags = pNew->wsFlags;
110173 110905     saved_prereq = pNew->prereq;
110174 110906     saved_nOut = pNew->nOut;
110175 110907     pNew->rSetup = 0;
110176         -  rLogSize = estLog(whereCost(pProbe->aiRowEst[0]));
       110908  +  rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
110177 110909     for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
110178 110910       int nIn = 0;
110179 110911   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110180 110912       int nRecValid = pBuilder->nRecValid;
110181 110913   #endif
110182 110914       if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
110183 110915        && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
................................................................................
110196 110928       pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
110197 110929       pNew->rRun = rLogSize; /* Baseline cost is log2(N).  Adjustments below */
110198 110930       if( pTerm->eOperator & WO_IN ){
110199 110931         Expr *pExpr = pTerm->pExpr;
110200 110932         pNew->wsFlags |= WHERE_COLUMN_IN;
110201 110933         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
110202 110934           /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
110203         -        nIn = 46;  assert( 46==whereCost(25) );
       110935  +        nIn = 46;  assert( 46==sqlite3LogEst(25) );
110204 110936         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
110205 110937           /* "x IN (value, value, ...)" */
110206         -        nIn = whereCost(pExpr->x.pList->nExpr);
       110938  +        nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
110207 110939         }
110208 110940         pNew->rRun += nIn;
110209 110941         pNew->u.btree.nEq++;
110210 110942         pNew->nOut = nRowEst + nInMul + nIn;
110211 110943       }else if( pTerm->eOperator & (WO_EQ) ){
110212 110944         assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
110213 110945                     || nInMul==0 );
................................................................................
110221 110953         }
110222 110954         pNew->u.btree.nEq++;
110223 110955         pNew->nOut = nRowEst + nInMul;
110224 110956       }else if( pTerm->eOperator & (WO_ISNULL) ){
110225 110957         pNew->wsFlags |= WHERE_COLUMN_NULL;
110226 110958         pNew->u.btree.nEq++;
110227 110959         /* TUNING: IS NULL selects 2 rows */
110228         -      nIn = 10;  assert( 10==whereCost(2) );
       110960  +      nIn = 10;  assert( 10==sqlite3LogEst(2) );
110229 110961         pNew->nOut = nRowEst + nInMul + nIn;
110230 110962       }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
110231 110963         testcase( pTerm->eOperator & WO_GT );
110232 110964         testcase( pTerm->eOperator & WO_GE );
110233 110965         pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
110234 110966         pBtm = pTerm;
110235 110967         pTop = 0;
................................................................................
110241 110973         pTop = pTerm;
110242 110974         pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
110243 110975                        pNew->aLTerm[pNew->nLTerm-2] : 0;
110244 110976       }
110245 110977       if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
110246 110978         /* Adjust nOut and rRun for STAT3 range values */
110247 110979         assert( pNew->nOut==saved_nOut );
110248         -      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, &pNew->nOut);
       110980  +      whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
110249 110981       }
110250 110982   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110251 110983       if( nInMul==0 
110252 110984        && pProbe->nSample 
110253 110985        && pNew->u.btree.nEq<=pProbe->nSampleCol
110254 110986        && OptimizationEnabled(db, SQLITE_Stat3) 
110255 110987       ){
................................................................................
110261 110993           rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
110262 110994         }else if( (pTerm->eOperator & WO_IN)
110263 110995                &&  !ExprHasProperty(pExpr, EP_xIsSelect)  ){
110264 110996           rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
110265 110997         }
110266 110998         assert( nOut==0 || rc==SQLITE_OK );
110267 110999         if( nOut ){
110268         -        nOut = whereCost(nOut);
110269         -        pNew->nOut = MIN(nOut, saved_nOut);
       111000  +        pNew->nOut = sqlite3LogEst(nOut);
       111001  +        if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
110270 111002         }
110271 111003       }
110272 111004   #endif
110273 111005       if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
110274 111006         /* Each row involves a step of the index, then a binary search of
110275 111007         ** the main table */
110276         -      pNew->rRun =  whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
       111008  +      pNew->rRun =  sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
110277 111009       }
110278 111010       /* Step cost for each output row */
110279         -    pNew->rRun = whereCostAdd(pNew->rRun, pNew->nOut);
110280         -    /* TBD: Adjust nOut for additional constraints */
       111011  +    pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
       111012  +    whereLoopOutputAdjust(pBuilder->pWC, pNew);
110281 111013       rc = whereLoopInsert(pBuilder, pNew);
110282 111014       if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
110283 111015        && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
110284 111016       ){
110285 111017         whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
110286 111018       }
110287 111019       pNew->nOut = saved_nOut;
................................................................................
110372 111104     int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
110373 111105     SrcList *pTabList;          /* The FROM clause */
110374 111106     struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
110375 111107     WhereLoop *pNew;            /* Template WhereLoop object */
110376 111108     int rc = SQLITE_OK;         /* Return code */
110377 111109     int iSortIdx = 1;           /* Index number */
110378 111110     int b;                      /* A boolean value */
110379         -  WhereCost rSize;            /* number of rows in the table */
110380         -  WhereCost rLogSize;         /* Logarithm of the number of rows in the table */
       111111  +  LogEst rSize;               /* number of rows in the table */
       111112  +  LogEst rLogSize;            /* Logarithm of the number of rows in the table */
110381 111113     WhereClause *pWC;           /* The parsed WHERE clause */
       111114  +  Table *pTab;                /* Table being queried */
110382 111115     
110383 111116     pNew = pBuilder->pNew;
110384 111117     pWInfo = pBuilder->pWInfo;
110385 111118     pTabList = pWInfo->pTabList;
110386 111119     pSrc = pTabList->a + pNew->iTab;
       111120  +  pTab = pSrc->pTab;
110387 111121     pWC = pBuilder->pWC;
110388 111122     assert( !IsVirtual(pSrc->pTab) );
110389 111123   
110390 111124     if( pSrc->pIndex ){
110391 111125       /* An INDEXED BY clause specifies a particular index to use */
110392 111126       pProbe = pSrc->pIndex;
110393 111127     }else{
................................................................................
110397 111131       ** indices to follow */
110398 111132       Index *pFirst;                  /* First of real indices on the table */
110399 111133       memset(&sPk, 0, sizeof(Index));
110400 111134       sPk.nColumn = 1;
110401 111135       sPk.aiColumn = &aiColumnPk;
110402 111136       sPk.aiRowEst = aiRowEstPk;
110403 111137       sPk.onError = OE_Replace;
110404         -    sPk.pTable = pSrc->pTab;
110405         -    aiRowEstPk[0] = pSrc->pTab->nRowEst;
       111138  +    sPk.pTable = pTab;
       111139  +    aiRowEstPk[0] = pTab->nRowEst;
110406 111140       aiRowEstPk[1] = 1;
110407 111141       pFirst = pSrc->pTab->pIndex;
110408 111142       if( pSrc->notIndexed==0 ){
110409 111143         /* The real indices of the table are only considered if the
110410 111144         ** NOT INDEXED qualifier is omitted from the FROM clause */
110411 111145         sPk.pNext = pFirst;
110412 111146       }
110413 111147       pProbe = &sPk;
110414 111148     }
110415         -  rSize = whereCost(pSrc->pTab->nRowEst);
       111149  +  rSize = sqlite3LogEst(pTab->nRowEst);
110416 111150     rLogSize = estLog(rSize);
110417 111151   
110418 111152   #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
110419 111153     /* Automatic indexes */
110420 111154     if( !pBuilder->pOrSet
110421 111155      && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
110422 111156      && pSrc->pIndex==0
................................................................................
110433 111167           pNew->u.btree.nEq = 1;
110434 111168           pNew->u.btree.pIndex = 0;
110435 111169           pNew->nLTerm = 1;
110436 111170           pNew->aLTerm[0] = pTerm;
110437 111171           /* TUNING: One-time cost for computing the automatic index is
110438 111172           ** approximately 7*N*log2(N) where N is the number of rows in
110439 111173           ** the table being indexed. */
110440         -        pNew->rSetup = rLogSize + rSize + 28;  assert( 28==whereCost(7) );
       111174  +        pNew->rSetup = rLogSize + rSize + 28;  assert( 28==sqlite3LogEst(7) );
110441 111175           /* TUNING: Each index lookup yields 20 rows in the table.  This
110442 111176           ** is more than the usual guess of 10 rows, since we have no way
110443 111177           ** of knowning how selective the index will ultimately be.  It would
110444 111178           ** not be unreasonable to make this value much larger. */
110445         -        pNew->nOut = 43;  assert( 43==whereCost(20) );
110446         -        pNew->rRun = whereCostAdd(rLogSize,pNew->nOut);
       111179  +        pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
       111180  +        pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
110447 111181           pNew->wsFlags = WHERE_AUTO_INDEX;
110448 111182           pNew->prereq = mExtra | pTerm->prereqRight;
110449 111183           rc = whereLoopInsert(pBuilder, pNew);
110450 111184         }
110451 111185       }
110452 111186     }
110453 111187   #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
................................................................................
110473 111207         /* Integer primary key index */
110474 111208         pNew->wsFlags = WHERE_IPK;
110475 111209   
110476 111210         /* Full table scan */
110477 111211         pNew->iSortIdx = b ? iSortIdx : 0;
110478 111212         /* TUNING: Cost of full table scan is 3*(N + log2(N)).
110479 111213         **  +  The extra 3 factor is to encourage the use of indexed lookups
110480         -      **     over full scans.  A smaller constant 2 is used for covering
110481         -      **     index scans so that a covering index scan will be favored over
110482         -      **     a table scan. */
110483         -      pNew->rRun = whereCostAdd(rSize,rLogSize) + 16;
       111214  +      **     over full scans.  FIXME */
       111215  +      pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
       111216  +      whereLoopOutputAdjust(pWC, pNew);
110484 111217         rc = whereLoopInsert(pBuilder, pNew);
       111218  +      pNew->nOut = rSize;
110485 111219         if( rc ) break;
110486 111220       }else{
110487 111221         Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
110488 111222         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
110489 111223   
110490 111224         /* Full scan via index */
110491 111225         if( b
110492 111226          || ( m==0
110493 111227            && pProbe->bUnordered==0
       111228  +         && pProbe->szIdxRow<pTab->szTabRow
110494 111229            && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
110495 111230            && sqlite3GlobalConfig.bUseCis
110496 111231            && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
110497 111232             )
110498 111233         ){
110499 111234           pNew->iSortIdx = b ? iSortIdx : 0;
110500 111235           if( m==0 ){
110501         -          /* TUNING: Cost of a covering index scan is 2*(N + log2(N)).
110502         -          **  +  The extra 2 factor is to encourage the use of indexed lookups
110503         -          **     over index scans.  A table scan uses a factor of 3 so that
110504         -          **     index scans are favored over table scans.
110505         -          **  +  If this covering index might also help satisfy the ORDER BY
110506         -          **     clause, then the cost is fudged down slightly so that this
110507         -          **     index is favored above other indices that have no hope of
110508         -          **     helping with the ORDER BY. */
110509         -          pNew->rRun = 10 + whereCostAdd(rSize,rLogSize) - b;
       111236  +          /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
       111237  +          **  +  The extra factor K of between 1.1 and 3.0 that depends
       111238  +          **     on the relative sizes of the table and the index.  K
       111239  +          **     is smaller for smaller indices, thus favoring them.
       111240  +          */
       111241  +          pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
       111242  +                        (15*pProbe->szIdxRow)/pTab->szTabRow;
110510 111243           }else{
110511 111244             assert( b!=0 ); 
110512 111245             /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
110513 111246             ** which we will simplify to just N*log2(N) */
110514 111247             pNew->rRun = rSize + rLogSize;
110515 111248           }
       111249  +        whereLoopOutputAdjust(pWC, pNew);
110516 111250           rc = whereLoopInsert(pBuilder, pNew);
       111251  +        pNew->nOut = rSize;
110517 111252           if( rc ) break;
110518 111253         }
110519 111254       }
110520 111255   
110521 111256       rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
110522 111257   #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
110523 111258       sqlite3Stat4ProbeFree(pBuilder->pRec);
................................................................................
110678 111413         pNew->u.vtab.idxNum = pIdxInfo->idxNum;
110679 111414         pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
110680 111415         pIdxInfo->needToFreeIdxStr = 0;
110681 111416         pNew->u.vtab.idxStr = pIdxInfo->idxStr;
110682 111417         pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
110683 111418                                        && pIdxInfo->orderByConsumed);
110684 111419         pNew->rSetup = 0;
110685         -      pNew->rRun = whereCostFromDouble(pIdxInfo->estimatedCost);
       111420  +      pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
110686 111421         /* TUNING: Every virtual table query returns 25 rows */
110687         -      pNew->nOut = 46;  assert( 46==whereCost(25) );
       111422  +      pNew->nOut = 46;  assert( 46==sqlite3LogEst(25) );
110688 111423         whereLoopInsert(pBuilder, pNew);
110689 111424         if( pNew->u.vtab.needFree ){
110690 111425           sqlite3_free(pNew->u.vtab.idxStr);
110691 111426           pNew->u.vtab.needFree = 0;
110692 111427         }
110693 111428       }
110694 111429     }  
................................................................................
110717 111452     struct SrcList_item *pItem;
110718 111453     
110719 111454     pWC = pBuilder->pWC;
110720 111455     if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
110721 111456     pWCEnd = pWC->a + pWC->nTerm;
110722 111457     pNew = pBuilder->pNew;
110723 111458     memset(&sSum, 0, sizeof(sSum));
       111459  +  pItem = pWInfo->pTabList->a + pNew->iTab;
       111460  +  iCur = pItem->iCursor;
110724 111461   
110725 111462     for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
110726 111463       if( (pTerm->eOperator & WO_OR)!=0
110727 111464        && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 
110728 111465       ){
110729 111466         WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
110730 111467         WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
110731 111468         WhereTerm *pOrTerm;
110732 111469         int once = 1;
110733 111470         int i, j;
110734 111471       
110735         -      pItem = pWInfo->pTabList->a + pNew->iTab;
110736         -      iCur = pItem->iCursor;
110737 111472         sSubBuild = *pBuilder;
110738 111473         sSubBuild.pOrderBy = 0;
110739 111474         sSubBuild.pOrSet = &sCur;
110740 111475   
110741 111476         for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
110742 111477           if( (pOrTerm->eOperator & WO_AND)!=0 ){
110743 111478             sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
................................................................................
110770 111505             once = 0;
110771 111506           }else{
110772 111507             whereOrMove(&sPrev, &sSum);
110773 111508             sSum.n = 0;
110774 111509             for(i=0; i<sPrev.n; i++){
110775 111510               for(j=0; j<sCur.n; j++){
110776 111511                 whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
110777         -                            whereCostAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
110778         -                            whereCostAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
       111512  +                            sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
       111513  +                            sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
110779 111514               }
110780 111515             }
110781 111516           }
110782 111517         }
110783 111518         pNew->nLTerm = 1;
110784 111519         pNew->aLTerm[0] = pTerm;
110785 111520         pNew->wsFlags = WHERE_MULTI_OR;
................................................................................
111109 111844   ** Assume that the total number of output rows that will need to be sorted
111110 111845   ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
111111 111846   ** costs if nRowEst==0.
111112 111847   **
111113 111848   ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
111114 111849   ** error occurs.
111115 111850   */
111116         -static int wherePathSolver(WhereInfo *pWInfo, WhereCost nRowEst){
       111851  +static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
111117 111852     int mxChoice;             /* Maximum number of simultaneous paths tracked */
111118 111853     int nLoop;                /* Number of terms in the join */
111119 111854     Parse *pParse;            /* Parsing context */
111120 111855     sqlite3 *db;              /* The database connection */
111121 111856     int iLoop;                /* Loop counter over the terms of the join */
111122 111857     int ii, jj;               /* Loop counters */
111123         -  WhereCost rCost;             /* Cost of a path */
111124         -  WhereCost mxCost = 0;        /* Maximum cost of a set of paths */
111125         -  WhereCost rSortCost;         /* Cost to do a sort */
       111858  +  int mxI = 0;              /* Index of next entry to replace */
       111859  +  LogEst rCost;             /* Cost of a path */
       111860  +  LogEst nOut;              /* Number of outputs */
       111861  +  LogEst mxCost = 0;        /* Maximum cost of a set of paths */
       111862  +  LogEst mxOut = 0;         /* Maximum nOut value on the set of paths */
       111863  +  LogEst rSortCost;         /* Cost to do a sort */
111126 111864     int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
111127 111865     WherePath *aFrom;         /* All nFrom paths at the previous level */
111128 111866     WherePath *aTo;           /* The nTo best paths at the current level */
111129 111867     WherePath *pFrom;         /* An element of aFrom[] that we are working on */
111130 111868     WherePath *pTo;           /* An element of aTo[] that we are working on */
111131 111869     WhereLoop *pWLoop;        /* One of the WhereLoop objects */
111132 111870     WhereLoop **pX;           /* Used to divy up the pSpace memory */
................................................................................
111155 111893     }
111156 111894   
111157 111895     /* Seed the search with a single WherePath containing zero WhereLoops.
111158 111896     **
111159 111897     ** TUNING: Do not let the number of iterations go above 25.  If the cost
111160 111898     ** of computing an automatic index is not paid back within the first 25
111161 111899     ** rows, then do not use the automatic index. */
111162         -  aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==whereCost(25) );
       111900  +  aFrom[0].nRow = MIN(pParse->nQueryLoop, 46);  assert( 46==sqlite3LogEst(25) );
111163 111901     nFrom = 1;
111164 111902   
111165 111903     /* Precompute the cost of sorting the final result set, if the caller
111166 111904     ** to sqlite3WhereBegin() was concerned about sorting */
111167 111905     rSortCost = 0;
111168 111906     if( pWInfo->pOrderBy==0 || nRowEst==0 ){
111169 111907       aFrom[0].isOrderedValid = 1;
111170 111908     }else{
111171         -    /* TUNING: Estimated cost of sorting is N*log2(N) where N is the
111172         -    ** number of output rows. */
       111909  +    /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
       111910  +    ** number of output rows. The 48 is the expected size of a row to sort. 
       111911  +    ** FIXME:  compute a better estimate of the 48 multiplier based on the
       111912  +    ** result set expressions. */
111173 111913       rSortCost = nRowEst + estLog(nRowEst);
111174 111914       WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
111175 111915     }
111176 111916   
111177 111917     /* Compute successively longer WherePaths using the previous generation
111178 111918     ** of WherePaths as the basis for the next.  Keep track of the mxChoice
111179 111919     ** best paths at each generation */
................................................................................
111185 111925           Bitmask revMask = 0;
111186 111926           u8 isOrderedValid = pFrom->isOrderedValid;
111187 111927           u8 isOrdered = pFrom->isOrdered;
111188 111928           if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
111189 111929           if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
111190 111930           /* At this point, pWLoop is a candidate to be the next loop. 
111191 111931           ** Compute its cost */
111192         -        rCost = whereCostAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
111193         -        rCost = whereCostAdd(rCost, pFrom->rCost);
       111932  +        rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
       111933  +        rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
       111934  +        nOut = pFrom->nRow + pWLoop->nOut;
111194 111935           maskNew = pFrom->maskLoop | pWLoop->maskSelf;
111195 111936           if( !isOrderedValid ){
111196 111937             switch( wherePathSatisfiesOrderBy(pWInfo,
111197 111938                          pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
111198 111939                          iLoop, pWLoop, &revMask) ){
111199 111940               case 1:  /* Yes.  pFrom+pWLoop does satisfy the ORDER BY clause */
111200 111941                 isOrdered = 1;
111201 111942                 isOrderedValid = 1;
111202 111943                 break;
111203 111944               case 0:  /* No.  pFrom+pWLoop will require a separate sort */
111204 111945                 isOrdered = 0;
111205 111946                 isOrderedValid = 1;
111206         -              rCost = whereCostAdd(rCost, rSortCost);
       111947  +              rCost = sqlite3LogEstAdd(rCost, rSortCost);
111207 111948                 break;
111208 111949               default: /* Cannot tell yet.  Try again on the next iteration */
111209 111950                 break;
111210 111951             }
111211 111952           }else{
111212 111953             revMask = pFrom->revLoop;
111213 111954           }
111214 111955           /* Check to see if pWLoop should be added to the mxChoice best so far */
111215 111956           for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
111216         -          if( pTo->maskLoop==maskNew && pTo->isOrderedValid==isOrderedValid ){
       111957  +          if( pTo->maskLoop==maskNew
       111958  +           && pTo->isOrderedValid==isOrderedValid
       111959  +           && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
       111960  +                (pTo->rCost>=rCost && pTo->nRow>=nOut))
       111961  +          ){
111217 111962               testcase( jj==nTo-1 );
111218 111963               break;
111219 111964             }
111220 111965           }
111221 111966           if( jj>=nTo ){
111222 111967             if( nTo>=mxChoice && rCost>=mxCost ){
111223 111968   #ifdef WHERETRACE_ENABLED
111224 111969               if( sqlite3WhereTrace&0x4 ){
111225         -              sqlite3DebugPrintf("Skip   %s cost=%3d order=%c\n",
111226         -                  wherePathName(pFrom, iLoop, pWLoop), rCost,
       111970  +              sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
       111971  +                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
111227 111972                     isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
111228 111973               }
111229 111974   #endif
111230 111975               continue;
111231 111976             }
111232 111977             /* Add a new Path to the aTo[] set */
111233 111978             if( nTo<mxChoice ){
111234 111979               /* Increase the size of the aTo set by one */
111235 111980               jj = nTo++;
111236 111981             }else{
111237 111982               /* New path replaces the prior worst to keep count below mxChoice */
111238         -            for(jj=nTo-1; aTo[jj].rCost<mxCost; jj--){ assert(jj>0); }
       111983  +            jj = mxI;
111239 111984             }
111240 111985             pTo = &aTo[jj];
111241 111986   #ifdef WHERETRACE_ENABLED
111242 111987             if( sqlite3WhereTrace&0x4 ){
111243         -            sqlite3DebugPrintf("New    %s cost=%-3d order=%c\n",
111244         -                wherePathName(pFrom, iLoop, pWLoop), rCost,
       111988  +            sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
       111989  +                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
111245 111990                   isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
111246 111991             }
111247 111992   #endif
111248 111993           }else{
111249         -          if( pTo->rCost<=rCost ){
       111994  +          if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
111250 111995   #ifdef WHERETRACE_ENABLED
111251 111996               if( sqlite3WhereTrace&0x4 ){
111252 111997                 sqlite3DebugPrintf(
111253         -                  "Skip   %s cost=%-3d order=%c",
111254         -                  wherePathName(pFrom, iLoop, pWLoop), rCost,
       111998  +                  "Skip   %s cost=%-3d,%3d order=%c",
       111999  +                  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
111255 112000                     isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
111256         -              sqlite3DebugPrintf("   vs %s cost=%-3d order=%c\n",
111257         -                  wherePathName(pTo, iLoop+1, 0), pTo->rCost,
       112001  +              sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
       112002  +                  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
111258 112003                     pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
111259 112004               }
111260 112005   #endif
111261 112006               testcase( pTo->rCost==rCost );
111262 112007               continue;
111263 112008             }
111264 112009             testcase( pTo->rCost==rCost+1 );
111265 112010             /* A new and better score for a previously created equivalent path */
111266 112011   #ifdef WHERETRACE_ENABLED
111267 112012             if( sqlite3WhereTrace&0x4 ){
111268 112013               sqlite3DebugPrintf(
111269         -                "Update %s cost=%-3d order=%c",
111270         -                wherePathName(pFrom, iLoop, pWLoop), rCost,
       112014  +                "Update %s cost=%-3d,%3d order=%c",
       112015  +                wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
111271 112016                   isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
111272         -            sqlite3DebugPrintf("  was %s cost=%-3d order=%c\n",
111273         -                wherePathName(pTo, iLoop+1, 0), pTo->rCost,
       112017  +            sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
       112018  +                wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
111274 112019                   pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
111275 112020             }
111276 112021   #endif
111277 112022           }
111278 112023           /* pWLoop is a winner.  Add it to the set of best so far */
111279 112024           pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
111280 112025           pTo->revLoop = revMask;
111281         -        pTo->nRow = pFrom->nRow + pWLoop->nOut;
       112026  +        pTo->nRow = nOut;
111282 112027           pTo->rCost = rCost;
111283 112028           pTo->isOrderedValid = isOrderedValid;
111284 112029           pTo->isOrdered = isOrdered;
111285 112030           memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
111286 112031           pTo->aLoop[iLoop] = pWLoop;
111287 112032           if( nTo>=mxChoice ){
       112033  +          mxI = 0;
111288 112034             mxCost = aTo[0].rCost;
       112035  +          mxOut = aTo[0].nRow;
111289 112036             for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
111290         -            if( pTo->rCost>mxCost ) mxCost = pTo->rCost;
       112037  +            if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
       112038  +              mxCost = pTo->rCost;
       112039  +              mxOut = pTo->nRow;
       112040  +              mxI = jj;
       112041  +            }
111291 112042             }
111292 112043           }
111293 112044         }
111294 112045       }
111295 112046   
111296 112047   #ifdef WHERETRACE_ENABLED
111297 112048       if( sqlite3WhereTrace>=2 ){
................................................................................
111320 112071       sqlite3ErrorMsg(pParse, "no query solution");
111321 112072       sqlite3DbFree(db, pSpace);
111322 112073       return SQLITE_ERROR;
111323 112074     }
111324 112075     
111325 112076     /* Find the lowest cost path.  pFrom will be left pointing to that path */
111326 112077     pFrom = aFrom;
111327         -  assert( nFrom==1 );
111328         -#if 0 /* The following is needed if nFrom is ever more than 1 */
111329 112078     for(ii=1; ii<nFrom; ii++){
111330 112079       if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
111331 112080     }
111332         -#endif
111333 112081     assert( pWInfo->nLevel==nLoop );
111334 112082     /* Load the lowest cost path into pWInfo */
111335 112083     for(iLoop=0; iLoop<nLoop; iLoop++){
111336 112084       WhereLevel *pLevel = pWInfo->a + iLoop;
111337 112085       pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
111338 112086       pLevel->iFrom = pWLoop->iTab;
111339 112087       pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
................................................................................
111399 112147     pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
111400 112148     if( pTerm ){
111401 112149       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
111402 112150       pLoop->aLTerm[0] = pTerm;
111403 112151       pLoop->nLTerm = 1;
111404 112152       pLoop->u.btree.nEq = 1;
111405 112153       /* TUNING: Cost of a rowid lookup is 10 */
111406         -    pLoop->rRun = 33;  /* 33==whereCost(10) */
       112154  +    pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
111407 112155     }else{
111408 112156       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111409 112157         assert( pLoop->aLTermSpace==pLoop->aLTerm );
111410 112158         assert( ArraySize(pLoop->aLTermSpace)==4 );
111411 112159         if( pIdx->onError==OE_None 
111412 112160          || pIdx->pPartIdxWhere!=0 
111413 112161          || pIdx->nColumn>ArraySize(pLoop->aLTermSpace) 
................................................................................
111422 112170         if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
111423 112171           pLoop->wsFlags |= WHERE_IDX_ONLY;
111424 112172         }
111425 112173         pLoop->nLTerm = j;
111426 112174         pLoop->u.btree.nEq = j;
111427 112175         pLoop->u.btree.pIndex = pIdx;
111428 112176         /* TUNING: Cost of a unique index lookup is 15 */
111429         -      pLoop->rRun = 39;  /* 39==whereCost(15) */
       112177  +      pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
111430 112178         break;
111431 112179       }
111432 112180     }
111433 112181     if( pLoop->wsFlags ){
111434         -    pLoop->nOut = (WhereCost)1;
       112182  +    pLoop->nOut = (LogEst)1;
111435 112183       pWInfo->a[0].pWLoop = pLoop;
111436 112184       pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
111437 112185       pWInfo->a[0].iTabCur = iCur;
111438 112186       pWInfo->nRowOut = 1;
111439 112187       if( pWInfo->pOrderBy ) pWInfo->bOBSat =  1;
111440 112188       if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
111441 112189         pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
................................................................................
111795 112543       }
111796 112544     }
111797 112545     WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
111798 112546     pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
111799 112547   
111800 112548     /* If the caller is an UPDATE or DELETE statement that is requesting
111801 112549     ** to use a one-pass algorithm, determine if this is appropriate.
111802         -  ** The one-pass algorithm only works if the WHERE clause constraints
       112550  +  ** The one-pass algorithm only works if the WHERE clause constrains
111803 112551     ** the statement to update a single row.
111804 112552     */
111805 112553     assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
111806 112554     if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 
111807 112555      && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
111808 112556       pWInfo->okOnePass = 1;
111809 112557       pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
................................................................................
114955 115703       }
114956 115704       yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
114957 115705       yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
114958 115706     }
114959 115707           break;
114960 115708         case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
114961 115709   {
114962         -  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
       115710  +  yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0);
114963 115711     if( yygotominor.yy342.pExpr ){
114964         -    yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
       115712  +    yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442;
114965 115713       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
114966 115714     }else{
114967 115715       sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
       115716  +    sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122);
114968 115717     }
114969 115718     yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
114970 115719     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
114971 115720   }
114972 115721           break;
114973 115722         case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
114974 115723   {
................................................................................
121212 121961     ** methods of the virtual table are called at appropriate times.  These
121213 121962     ** values do not contribute to FTS functionality; they are used for
121214 121963     ** verifying the operation of the SQLite core.
121215 121964     */
121216 121965     int inTransaction;     /* True after xBegin but before xCommit/xRollback */
121217 121966     int mxSavepoint;       /* Largest valid xSavepoint integer */
121218 121967   #endif
       121968  +
       121969  +#ifdef SQLITE_TEST
       121970  +  /* True to disable the incremental doclist optimization. This is controled
       121971  +  ** by special insert command 'test-no-incr-doclist'.  */
       121972  +  int bNoIncrDoclist;
       121973  +#endif
121219 121974   };
121220 121975   
121221 121976   /*
121222 121977   ** When the core wants to read from the virtual table, it creates a
121223 121978   ** virtual table cursor (an instance of the following structure) using
121224 121979   ** the xOpen method. Cursors are destroyed using the xClose method.
121225 121980   */
................................................................................
121237 121992     char *pNextId;                  /* Pointer into the body of aDoclist */
121238 121993     char *aDoclist;                 /* List of docids for full-text queries */
121239 121994     int nDoclist;                   /* Size of buffer at aDoclist */
121240 121995     u8 bDesc;                       /* True to sort in descending order */
121241 121996     int eEvalmode;                  /* An FTS3_EVAL_XX constant */
121242 121997     int nRowAvg;                    /* Average size of database rows, in pages */
121243 121998     sqlite3_int64 nDoc;             /* Documents in table */
121244         -
       121999  +  i64 iMinDocid;                  /* Minimum docid to return */
       122000  +  i64 iMaxDocid;                  /* Maximum docid to return */
121245 122001     int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
121246 122002     u32 *aMatchinfo;                /* Information about most recent match */
121247 122003     int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
121248 122004     char *zMatchinfo;               /* Matchinfo specification */
121249 122005   };
121250 122006   
121251 122007   #define FTS3_EVAL_FILTER    0
................................................................................
121267 122023   ** indicating that all columns should be searched,
121268 122024   ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
121269 122025   */
121270 122026   #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
121271 122027   #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
121272 122028   #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
121273 122029   
       122030  +/*
       122031  +** The lower 16-bits of the sqlite3_index_info.idxNum value set by
       122032  +** the xBestIndex() method contains the Fts3Cursor.eSearch value described
       122033  +** above. The upper 16-bits contain a combination of the following
       122034  +** bits, used to describe extra constraints on full-text searches.
       122035  +*/
       122036  +#define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
       122037  +#define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
       122038  +#define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
121274 122039   
121275 122040   struct Fts3Doclist {
121276 122041     char *aAll;                    /* Array containing doclist (or NULL) */
121277 122042     int nAll;                      /* Size of a[] in bytes */
121278 122043     char *pNextDocid;              /* Pointer to next docid */
121279 122044   
121280 122045     sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
................................................................................
122687 123452   **   2. Full-text search using a MATCH operator on a non-docid column.
122688 123453   **   3. Linear scan of %_content table.
122689 123454   */
122690 123455   static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
122691 123456     Fts3Table *p = (Fts3Table *)pVTab;
122692 123457     int i;                          /* Iterator variable */
122693 123458     int iCons = -1;                 /* Index of constraint to use */
       123459  +
122694 123460     int iLangidCons = -1;           /* Index of langid=x constraint, if present */
       123461  +  int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
       123462  +  int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
       123463  +  int iIdx;
122695 123464   
122696 123465     /* By default use a full table scan. This is an expensive option,
122697 123466     ** so search through the constraints to see if a more efficient 
122698 123467     ** strategy is possible.
122699 123468     */
122700 123469     pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
122701 123470     pInfo->estimatedCost = 5000000;
122702 123471     for(i=0; i<pInfo->nConstraint; i++){
       123472  +    int bDocid;                 /* True if this constraint is on docid */
122703 123473       struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
122704 123474       if( pCons->usable==0 ) continue;
       123475  +
       123476  +    bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
122705 123477   
122706 123478       /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
122707         -    if( iCons<0 
122708         -     && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
122709         -     && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
122710         -    ){
       123479  +    if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
122711 123480         pInfo->idxNum = FTS3_DOCID_SEARCH;
122712 123481         pInfo->estimatedCost = 1.0;
122713 123482         iCons = i;
122714 123483       }
122715 123484   
122716 123485       /* A MATCH constraint. Use a full-text search.
122717 123486       **
................................................................................
122732 123501   
122733 123502       /* Equality constraint on the langid column */
122734 123503       if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
122735 123504        && pCons->iColumn==p->nColumn + 2
122736 123505       ){
122737 123506         iLangidCons = i;
122738 123507       }
       123508  +
       123509  +    if( bDocid ){
       123510  +      switch( pCons->op ){
       123511  +        case SQLITE_INDEX_CONSTRAINT_GE:
       123512  +        case SQLITE_INDEX_CONSTRAINT_GT:
       123513  +          iDocidGe = i;
       123514  +          break;
       123515  +
       123516  +        case SQLITE_INDEX_CONSTRAINT_LE:
       123517  +        case SQLITE_INDEX_CONSTRAINT_LT:
       123518  +          iDocidLe = i;
       123519  +          break;
       123520  +      }
       123521  +    }
122739 123522     }
122740 123523   
       123524  +  iIdx = 1;
122741 123525     if( iCons>=0 ){
122742         -    pInfo->aConstraintUsage[iCons].argvIndex = 1;
       123526  +    pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
122743 123527       pInfo->aConstraintUsage[iCons].omit = 1;
122744 123528     } 
122745 123529     if( iLangidCons>=0 ){
122746         -    pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
       123530  +    pInfo->idxNum |= FTS3_HAVE_LANGID;
       123531  +    pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
       123532  +  } 
       123533  +  if( iDocidGe>=0 ){
       123534  +    pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
       123535  +    pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
       123536  +  } 
       123537  +  if( iDocidLe>=0 ){
       123538  +    pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
       123539  +    pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
122747 123540     } 
122748 123541   
122749 123542     /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
122750 123543     ** docid) order. Both ascending and descending are possible. 
122751 123544     */
122752 123545     if( pInfo->nOrderBy==1 ){
122753 123546       struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
................................................................................
124185 124978       }
124186 124979     }else{
124187 124980       rc = fts3EvalNext((Fts3Cursor *)pCursor);
124188 124981     }
124189 124982     assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
124190 124983     return rc;
124191 124984   }
       124985  +
       124986  +/*
       124987  +** The following are copied from sqliteInt.h.
       124988  +**
       124989  +** Constants for the largest and smallest possible 64-bit signed integers.
       124990  +** These macros are designed to work correctly on both 32-bit and 64-bit
       124991  +** compilers.
       124992  +*/
       124993  +#ifndef SQLITE_AMALGAMATION
       124994  +# define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
       124995  +# define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
       124996  +#endif
       124997  +
       124998  +/*
       124999  +** If the numeric type of argument pVal is "integer", then return it
       125000  +** converted to a 64-bit signed integer. Otherwise, return a copy of
       125001  +** the second parameter, iDefault.
       125002  +*/
       125003  +static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
       125004  +  if( pVal ){
       125005  +    int eType = sqlite3_value_numeric_type(pVal);
       125006  +    if( eType==SQLITE_INTEGER ){
       125007  +      return sqlite3_value_int64(pVal);
       125008  +    }
       125009  +  }
       125010  +  return iDefault;
       125011  +}
124192 125012   
124193 125013   /*
124194 125014   ** This is the xFilter interface for the virtual table.  See
124195 125015   ** the virtual table xFilter method documentation for additional
124196 125016   ** information.
124197 125017   **
124198 125018   ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
................................................................................
124211 125031     int idxNum,                     /* Strategy index */
124212 125032     const char *idxStr,             /* Unused */
124213 125033     int nVal,                       /* Number of elements in apVal */
124214 125034     sqlite3_value **apVal           /* Arguments for the indexing scheme */
124215 125035   ){
124216 125036     int rc;
124217 125037     char *zSql;                     /* SQL statement used to access %_content */
       125038  +  int eSearch;
124218 125039     Fts3Table *p = (Fts3Table *)pCursor->pVtab;
124219 125040     Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
       125041  +
       125042  +  sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
       125043  +  sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
       125044  +  sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
       125045  +  sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
       125046  +  int iIdx;
124220 125047   
124221 125048     UNUSED_PARAMETER(idxStr);
124222 125049     UNUSED_PARAMETER(nVal);
124223 125050   
124224         -  assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
124225         -  assert( nVal==0 || nVal==1 || nVal==2 );
124226         -  assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
       125051  +  eSearch = (idxNum & 0x0000FFFF);
       125052  +  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
124227 125053     assert( p->pSegments==0 );
       125054  +
       125055  +  /* Collect arguments into local variables */
       125056  +  iIdx = 0;
       125057  +  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
       125058  +  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
       125059  +  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
       125060  +  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
       125061  +  assert( iIdx==nVal );
124228 125062   
124229 125063     /* In case the cursor has been used before, clear it now. */
124230 125064     sqlite3_finalize(pCsr->pStmt);
124231 125065     sqlite3_free(pCsr->aDoclist);
124232 125066     sqlite3Fts3ExprFree(pCsr->pExpr);
124233 125067     memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
124234 125068   
       125069  +  /* Set the lower and upper bounds on docids to return */
       125070  +  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
       125071  +  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
       125072  +
124235 125073     if( idxStr ){
124236 125074       pCsr->bDesc = (idxStr[0]=='D');
124237 125075     }else{
124238 125076       pCsr->bDesc = p->bDescIdx;
124239 125077     }
124240         -  pCsr->eSearch = (i16)idxNum;
       125078  +  pCsr->eSearch = (i16)eSearch;
124241 125079   
124242         -  if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
124243         -    int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
124244         -    const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
       125080  +  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
       125081  +    int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
       125082  +    const char *zQuery = (const char *)sqlite3_value_text(pCons);
124245 125083   
124246         -    if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
       125084  +    if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
124247 125085         return SQLITE_NOMEM;
124248 125086       }
124249 125087   
124250 125088       pCsr->iLangid = 0;
124251         -    if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
       125089  +    if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
124252 125090   
124253 125091       assert( p->base.zErrMsg==0 );
124254 125092       rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
124255 125093           p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 
124256 125094           &p->base.zErrMsg
124257 125095       );
124258 125096       if( rc!=SQLITE_OK ){
................................................................................
124267 125105     }
124268 125106   
124269 125107     /* Compile a SELECT statement for this cursor. For a full-table-scan, the
124270 125108     ** statement loops through all rows of the %_content table. For a
124271 125109     ** full-text query or docid lookup, the statement retrieves a single
124272 125110     ** row by docid.
124273 125111     */
124274         -  if( idxNum==FTS3_FULLSCAN_SEARCH ){
       125112  +  if( eSearch==FTS3_FULLSCAN_SEARCH ){
124275 125113       zSql = sqlite3_mprintf(
124276 125114           "SELECT %s ORDER BY rowid %s",
124277 125115           p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
124278 125116       );
124279 125117       if( zSql ){
124280 125118         rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
124281 125119         sqlite3_free(zSql);
124282 125120       }else{
124283 125121         rc = SQLITE_NOMEM;
124284 125122       }
124285         -  }else if( idxNum==FTS3_DOCID_SEARCH ){
       125123  +  }else if( eSearch==FTS3_DOCID_SEARCH ){
124286 125124       rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
124287 125125       if( rc==SQLITE_OK ){
124288         -      rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
       125126  +      rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
124289 125127       }
124290 125128     }
124291 125129     if( rc!=SQLITE_OK ) return rc;
124292 125130   
124293 125131     return fts3NextMethod(pCursor);
124294 125132   }
124295 125133   
................................................................................
125172 126010         sqlite3_free(aPoslist);
125173 126011       }
125174 126012     }
125175 126013   
125176 126014     return SQLITE_OK;
125177 126015   }
125178 126016   
       126017  +/*
       126018  +** Maximum number of tokens a phrase may have to be considered for the
       126019  +** incremental doclists strategy.
       126020  +*/
       126021  +#define MAX_INCR_PHRASE_TOKENS 4
       126022  +
125179 126023   /*
125180 126024   ** This function is called for each Fts3Phrase in a full-text query 
125181 126025   ** expression to initialize the mechanism for returning rows. Once this
125182 126026   ** function has been called successfully on an Fts3Phrase, it may be
125183 126027   ** used with fts3EvalPhraseNext() to iterate through the matching docids.
125184 126028   **
125185 126029   ** If parameter bOptOk is true, then the phrase may (or may not) use the
125186 126030   ** incremental loading strategy. Otherwise, the entire doclist is loaded into
125187 126031   ** memory within this call.
125188 126032   **
125189 126033   ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
125190 126034   */
125191 126035   static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
125192         -  int rc;                         /* Error code */
125193         -  Fts3PhraseToken *pFirst = &p->aToken[0];
125194 126036     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
       126037  +  int rc = SQLITE_OK;             /* Error code */
       126038  +  int i;
125195 126039   
125196         -  if( pCsr->bDesc==pTab->bDescIdx 
125197         -   && bOptOk==1 
125198         -   && p->nToken==1 
125199         -   && pFirst->pSegcsr 
125200         -   && pFirst->pSegcsr->bLookup 
125201         -   && pFirst->bFirst==0
125202         -  ){
       126040  +  /* Determine if doclists may be loaded from disk incrementally. This is
       126041  +  ** possible if the bOptOk argument is true, the FTS doclists will be
       126042  +  ** scanned in forward order, and the phrase consists of 
       126043  +  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
       126044  +  ** tokens or prefix tokens that cannot use a prefix-index.  */
       126045  +  int bHaveIncr = 0;
       126046  +  int bIncrOk = (bOptOk 
       126047  +   && pCsr->bDesc==pTab->bDescIdx 
       126048  +   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
       126049  +   && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
       126050  +#ifdef SQLITE_TEST
       126051  +   && pTab->bNoIncrDoclist==0
       126052  +#endif
       126053  +  );
       126054  +  for(i=0; bIncrOk==1 && i<p->nToken; i++){
       126055  +    Fts3PhraseToken *pToken = &p->aToken[i];
       126056  +    if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
       126057  +      bIncrOk = 0;
       126058  +    }
       126059  +    if( pToken->pSegcsr ) bHaveIncr = 1;
       126060  +  }
       126061  +
       126062  +  if( bIncrOk && bHaveIncr ){
125203 126063       /* Use the incremental approach. */
125204 126064       int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
125205         -    rc = sqlite3Fts3MsrIncrStart(
125206         -        pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
       126065  +    for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
       126066  +      Fts3PhraseToken *pToken = &p->aToken[i];
       126067  +      Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
       126068  +      if( pSegcsr ){
       126069  +        rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
       126070  +      }
       126071  +    }
125207 126072       p->bIncr = 1;
125208         -
125209 126073     }else{
125210 126074       /* Load the full doclist for the phrase into memory. */
125211 126075       rc = fts3EvalPhraseLoad(pCsr, p);
125212 126076       p->bIncr = 0;
125213 126077     }
125214 126078   
125215 126079     assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
................................................................................
125309 126173         p += sqlite3Fts3GetVarint(p, &iVar);
125310 126174         *piDocid += ((bDescIdx ? -1 : 1) * iVar);
125311 126175       }
125312 126176     }
125313 126177   
125314 126178     *ppIter = p;
125315 126179   }
       126180  +
       126181  +/*
       126182  +** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
       126183  +** to true if EOF is reached.
       126184  +*/
       126185  +static void fts3EvalDlPhraseNext(
       126186  +  Fts3Table *pTab,
       126187  +  Fts3Doclist *pDL,
       126188  +  u8 *pbEof
       126189  +){
       126190  +  char *pIter;                            /* Used to iterate through aAll */
       126191  +  char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
       126192  + 
       126193  +  if( pDL->pNextDocid ){
       126194  +    pIter = pDL->pNextDocid;
       126195  +  }else{
       126196  +    pIter = pDL->aAll;
       126197  +  }
       126198  +
       126199  +  if( pIter>=pEnd ){
       126200  +    /* We have already reached the end of this doclist. EOF. */
       126201  +    *pbEof = 1;
       126202  +  }else{
       126203  +    sqlite3_int64 iDelta;
       126204  +    pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
       126205  +    if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
       126206  +      pDL->iDocid += iDelta;
       126207  +    }else{
       126208  +      pDL->iDocid -= iDelta;
       126209  +    }
       126210  +    pDL->pList = pIter;
       126211  +    fts3PoslistCopy(0, &pIter);
       126212  +    pDL->nList = (int)(pIter - pDL->pList);
       126213  +
       126214  +    /* pIter now points just past the 0x00 that terminates the position-
       126215  +    ** list for document pDL->iDocid. However, if this position-list was
       126216  +    ** edited in place by fts3EvalNearTrim(), then pIter may not actually
       126217  +    ** point to the start of the next docid value. The following line deals
       126218  +    ** with this case by advancing pIter past the zero-padding added by
       126219  +    ** fts3EvalNearTrim().  */
       126220  +    while( pIter<pEnd && *pIter==0 ) pIter++;
       126221  +
       126222  +    pDL->pNextDocid = pIter;
       126223  +    assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
       126224  +    *pbEof = 0;
       126225  +  }
       126226  +}
       126227  +
       126228  +/*
       126229  +** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
       126230  +*/
       126231  +typedef struct TokenDoclist TokenDoclist;
       126232  +struct TokenDoclist {
       126233  +  int bIgnore;
       126234  +  sqlite3_int64 iDocid;
       126235  +  char *pList;
       126236  +  int nList;
       126237  +};
       126238  +
       126239  +/*
       126240  +** Token pToken is an incrementally loaded token that is part of a 
       126241  +** multi-token phrase. Advance it to the next matching document in the
       126242  +** database and populate output variable *p with the details of the new
       126243  +** entry. Or, if the iterator has reached EOF, set *pbEof to true.
       126244  +**
       126245  +** If an error occurs, return an SQLite error code. Otherwise, return 
       126246  +** SQLITE_OK.
       126247  +*/
       126248  +static int incrPhraseTokenNext(
       126249  +  Fts3Table *pTab,                /* Virtual table handle */
       126250  +  Fts3Phrase *pPhrase,            /* Phrase to advance token of */
       126251  +  int iToken,                     /* Specific token to advance */
       126252  +  TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
       126253  +  u8 *pbEof                       /* OUT: True if iterator is at EOF */
       126254  +){
       126255  +  int rc = SQLITE_OK;
       126256  +
       126257  +  if( pPhrase->iDoclistToken==iToken ){
       126258  +    assert( p->bIgnore==0 );
       126259  +    assert( pPhrase->aToken[iToken].pSegcsr==0 );
       126260  +    fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
       126261  +    p->pList = pPhrase->doclist.pList;
       126262  +    p->nList = pPhrase->doclist.nList;
       126263  +    p->iDocid = pPhrase->doclist.iDocid;
       126264  +  }else{
       126265  +    Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
       126266  +    assert( pToken->pDeferred==0 );
       126267  +    assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
       126268  +    if( pToken->pSegcsr ){
       126269  +      assert( p->bIgnore==0 );
       126270  +      rc = sqlite3Fts3MsrIncrNext(
       126271  +          pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
       126272  +      );
       126273  +      if( p->pList==0 ) *pbEof = 1;
       126274  +    }else{
       126275  +      p->bIgnore = 1;
       126276  +    }
       126277  +  }
       126278  +
       126279  +  return rc;
       126280  +}
       126281  +
       126282  +
       126283  +/*
       126284  +** The phrase iterator passed as the second argument:
       126285  +**
       126286  +**   * features at least one token that uses an incremental doclist, and 
       126287  +**
       126288  +**   * does not contain any deferred tokens.
       126289  +**
       126290  +** Advance it to the next matching documnent in the database and populate
       126291  +** the Fts3Doclist.pList and nList fields. 
       126292  +**
       126293  +** If there is no "next" entry and no error occurs, then *pbEof is set to
       126294  +** 1 before returning. Otherwise, if no error occurs and the iterator is
       126295  +** successfully advanced, *pbEof is set to 0.
       126296  +**
       126297  +** If an error occurs, return an SQLite error code. Otherwise, return 
       126298  +** SQLITE_OK.
       126299  +*/
       126300  +static int fts3EvalIncrPhraseNext(
       126301  +  Fts3Cursor *pCsr,               /* FTS Cursor handle */
       126302  +  Fts3Phrase *p,                  /* Phrase object to advance to next docid */
       126303  +  u8 *pbEof                       /* OUT: Set to 1 if EOF */
       126304  +){
       126305  +  int rc = SQLITE_OK;
       126306  +  Fts3Doclist *pDL = &p->doclist;
       126307  +  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
       126308  +  u8 bEof = 0;
       126309  +
       126310  +  /* This is only called if it is guaranteed that the phrase has at least
       126311  +  ** one incremental token. In which case the bIncr flag is set. */
       126312  +  assert( p->bIncr==1 );
       126313  +
       126314  +  if( p->nToken==1 && p->bIncr ){
       126315  +    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
       126316  +        &pDL->iDocid, &pDL->pList, &pDL->nList
       126317  +    );
       126318  +    if( pDL->pList==0 ) bEof = 1;
       126319  +  }else{
       126320  +    int bDescDoclist = pCsr->bDesc;
       126321  +    struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
       126322  +
       126323  +    memset(a, 0, sizeof(a));
       126324  +    assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
       126325  +    assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
       126326  +
       126327  +    while( bEof==0 ){
       126328  +      int bMaxSet = 0;
       126329  +      sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
       126330  +      int i;                      /* Used to iterate through tokens */
       126331  +
       126332  +      /* Advance the iterator for each token in the phrase once. */
       126333  +      for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
       126334  +        rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
       126335  +        if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
       126336  +          iMax = a[i].iDocid;
       126337  +          bMaxSet = 1;
       126338  +        }
       126339  +      }
       126340  +      assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
       126341  +      assert( rc!=SQLITE_OK || bMaxSet );
       126342  +
       126343  +      /* Keep advancing iterators until they all point to the same document */
       126344  +      for(i=0; i<p->nToken; i++){
       126345  +        while( rc==SQLITE_OK && bEof==0 
       126346  +            && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 
       126347  +        ){
       126348  +          rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
       126349  +          if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
       126350  +            iMax = a[i].iDocid;
       126351  +            i = 0;
       126352  +          }
       126353  +        }
       126354  +      }
       126355  +
       126356  +      /* Check if the current entries really are a phrase match */
       126357  +      if( bEof==0 ){
       126358  +        int nList = 0;
       126359  +        int nByte = a[p->nToken-1].nList;
       126360  +        char *aDoclist = sqlite3_malloc(nByte+1);
       126361  +        if( !aDoclist ) return SQLITE_NOMEM;
       126362  +        memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
       126363  +
       126364  +        for(i=0; i<(p->nToken-1); i++){
       126365  +          if( a[i].bIgnore==0 ){
       126366  +            char *pL = a[i].pList;
       126367  +            char *pR = aDoclist;
       126368  +            char *pOut = aDoclist;
       126369  +            int nDist = p->nToken-1-i;
       126370  +            int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
       126371  +            if( res==0 ) break;
       126372  +            nList = (int)(pOut - aDoclist);
       126373  +          }
       126374  +        }
       126375  +        if( i==(p->nToken-1) ){
       126376  +          pDL->iDocid = iMax;
       126377  +          pDL->pList = aDoclist;
       126378  +          pDL->nList = nList;
       126379  +          pDL->bFreeList = 1;
       126380  +          break;
       126381  +        }
       126382  +        sqlite3_free(aDoclist);
       126383  +      }
       126384  +    }
       126385  +  }
       126386  +
       126387  +  *pbEof = bEof;
       126388  +  return rc;
       126389  +}
125316 126390   
125317 126391   /*
125318 126392   ** Attempt to move the phrase iterator to point to the next matching docid. 
125319 126393   ** If an error occurs, return an SQLite error code. Otherwise, return 
125320 126394   ** SQLITE_OK.
125321 126395   **
125322 126396   ** If there is no "next" entry and no error occurs, then *pbEof is set to
................................................................................
125329 126403     u8 *pbEof                       /* OUT: Set to 1 if EOF */
125330 126404   ){
125331 126405     int rc = SQLITE_OK;
125332 126406     Fts3Doclist *pDL = &p->doclist;
125333 126407     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
125334 126408   
125335 126409     if( p->bIncr ){
125336         -    assert( p->nToken==1 );
125337         -    assert( pDL->pNextDocid==0 );
125338         -    rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
125339         -        &pDL->iDocid, &pDL->pList, &pDL->nList
125340         -    );
125341         -    if( rc==SQLITE_OK && !pDL->pList ){
125342         -      *pbEof = 1;
125343         -    }
       126410  +    rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
125344 126411     }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
125345 126412       sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
125346 126413           &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
125347 126414       );
125348 126415       pDL->pList = pDL->pNextDocid;
125349 126416     }else{
125350         -    char *pIter;                            /* Used to iterate through aAll */
125351         -    char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
125352         -    if( pDL->pNextDocid ){
125353         -      pIter = pDL->pNextDocid;
125354         -    }else{
125355         -      pIter = pDL->aAll;
125356         -    }
125357         -
125358         -    if( pIter>=pEnd ){
125359         -      /* We have already reached the end of this doclist. EOF. */
125360         -      *pbEof = 1;
125361         -    }else{
125362         -      sqlite3_int64 iDelta;
125363         -      pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
125364         -      if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
125365         -        pDL->iDocid += iDelta;
125366         -      }else{
125367         -        pDL->iDocid -= iDelta;
125368         -      }
125369         -      pDL->pList = pIter;
125370         -      fts3PoslistCopy(0, &pIter);
125371         -      pDL->nList = (int)(pIter - pDL->pList);
125372         -
125373         -      /* pIter now points just past the 0x00 that terminates the position-
125374         -      ** list for document pDL->iDocid. However, if this position-list was
125375         -      ** edited in place by fts3EvalNearTrim(), then pIter may not actually
125376         -      ** point to the start of the next docid value. The following line deals
125377         -      ** with this case by advancing pIter past the zero-padding added by
125378         -      ** fts3EvalNearTrim().  */
125379         -      while( pIter<pEnd && *pIter==0 ) pIter++;
125380         -
125381         -      pDL->pNextDocid = pIter;
125382         -      assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
125383         -      *pbEof = 0;
125384         -    }
       126417  +    fts3EvalDlPhraseNext(pTab, pDL, pbEof);
125385 126418     }
125386 126419   
125387 126420     return rc;
125388 126421   }
125389 126422   
125390 126423   /*
125391 126424   **
................................................................................
125402 126435   **
125403 126436   ** If an error occurs within this function, *pRc is set to an SQLite error
125404 126437   ** code before returning.
125405 126438   */
125406 126439   static void fts3EvalStartReaders(
125407 126440     Fts3Cursor *pCsr,               /* FTS Cursor handle */
125408 126441     Fts3Expr *pExpr,                /* Expression to initialize phrases in */
125409         -  int bOptOk,                     /* True to enable incremental loading */
125410 126442     int *pRc                        /* IN/OUT: Error code */
125411 126443   ){
125412 126444     if( pExpr && SQLITE_OK==*pRc ){
125413 126445       if( pExpr->eType==FTSQUERY_PHRASE ){
125414 126446         int i;
125415 126447         int nToken = pExpr->pPhrase->nToken;
125416 126448         for(i=0; i<nToken; i++){
125417 126449           if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
125418 126450         }
125419 126451         pExpr->bDeferred = (i==nToken);
125420         -      *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
       126452  +      *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
125421 126453       }else{
125422         -      fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
125423         -      fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
       126454  +      fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
       126455  +      fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
125424 126456         pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
125425 126457       }
125426 126458     }
125427 126459   }
125428 126460   
125429 126461   /*
125430 126462   ** An array of the following structures is assembled as part of the process
................................................................................
125658 126690         pToken->pSegcsr = 0;
125659 126691       }else{
125660 126692         /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
125661 126693         ** for-loop. Except, limit the value to 2^24 to prevent it from 
125662 126694         ** overflowing the 32-bit integer it is stored in. */
125663 126695         if( ii<12 ) nLoad4 = nLoad4*4;
125664 126696   
125665         -      if( ii==0 || pTC->pPhrase->nToken>1 ){
       126697  +      if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
125666 126698           /* Either this is the cheapest token in the entire query, or it is
125667 126699           ** part of a multi-token phrase. Either way, the entire doclist will
125668 126700           ** (eventually) be loaded into memory. It may as well be now. */
125669 126701           Fts3PhraseToken *pToken = pTC->pToken;
125670 126702           int nList = 0;
125671 126703           char *pList = 0;
125672 126704           rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
................................................................................
125738 126770         }
125739 126771   
125740 126772         sqlite3_free(aTC);
125741 126773       }
125742 126774     }
125743 126775   #endif
125744 126776   
125745         -  fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
       126777  +  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
125746 126778     return rc;
125747 126779   }
125748 126780   
125749 126781   /*
125750 126782   ** Invalidate the current position list for phrase pPhrase.
125751 126783   */
125752 126784   static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
................................................................................
126221 127253         fts3EvalNextRow(pCsr, pExpr, &rc);
126222 127254         pCsr->isEof = pExpr->bEof;
126223 127255         pCsr->isRequireSeek = 1;
126224 127256         pCsr->isMatchinfoNeeded = 1;
126225 127257         pCsr->iPrevId = pExpr->iDocid;
126226 127258       }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
126227 127259     }
       127260  +
       127261  +  /* Check if the cursor is past the end of the docid range specified
       127262  +  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
       127263  +  if( rc==SQLITE_OK && (
       127264  +        (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
       127265  +     || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
       127266  +  )){
       127267  +    pCsr->isEof = 1;
       127268  +  }
       127269  +
126228 127270     return rc;
126229 127271   }
126230 127272   
126231 127273   /*
126232 127274   ** Restart interation for expression pExpr so that the next call to
126233 127275   ** fts3EvalNext() visits the first row. Do not allow incremental 
126234 127276   ** loading or merging of phrase doclists for this iteration.
................................................................................
126244 127286   ){
126245 127287     if( pExpr && *pRc==SQLITE_OK ){
126246 127288       Fts3Phrase *pPhrase = pExpr->pPhrase;
126247 127289   
126248 127290       if( pPhrase ){
126249 127291         fts3EvalInvalidatePoslist(pPhrase);
126250 127292         if( pPhrase->bIncr ){
126251         -        assert( pPhrase->nToken==1 );
126252         -        assert( pPhrase->aToken[0].pSegcsr );
126253         -        sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
       127293  +        int i;
       127294  +        for(i=0; i<pPhrase->nToken; i++){
       127295  +          Fts3PhraseToken *pToken = &pPhrase->aToken[i];
       127296  +          assert( pToken->pDeferred==0 );
       127297  +          if( pToken->pSegcsr ){
       127298  +            sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
       127299  +          }
       127300  +        }
126254 127301           *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
126255 127302         }
126256         -
126257 127303         pPhrase->doclist.pNextDocid = 0;
126258 127304         pPhrase->doclist.iDocid = 0;
126259 127305       }
126260 127306   
126261 127307       pExpr->iDocid = 0;
126262 127308       pExpr->bEof = 0;
126263 127309       pExpr->bStart = 0;
................................................................................
126498 127544       return SQLITE_OK;
126499 127545     }
126500 127546   
126501 127547     iDocid = pExpr->iDocid;
126502 127548     pIter = pPhrase->doclist.pList;
126503 127549     if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
126504 127550       int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
       127551  +    int iMul;                     /* +1 if csr dir matches index dir, else -1 */
126505 127552       int bOr = 0;
126506 127553       u8 bEof = 0;
126507         -    Fts3Expr *p;
       127554  +    u8 bTreeEof = 0;
       127555  +    Fts3Expr *p;                  /* Used to iterate from pExpr to root */
       127556  +    Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
126508 127557   
126509 127558       /* Check if this phrase descends from an OR expression node. If not, 
126510 127559       ** return NULL. Otherwise, the entry that corresponds to docid 
126511         -    ** pCsr->iPrevId may lie earlier in the doclist buffer. */
       127560  +    ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
       127561  +    ** tree that the node is part of has been marked as EOF, but the node
       127562  +    ** itself is not EOF, then it may point to an earlier entry. */
       127563  +    pNear = pExpr;
126512 127564       for(p=pExpr->pParent; p; p=p->pParent){
126513 127565         if( p->eType==FTSQUERY_OR ) bOr = 1;
       127566  +      if( p->eType==FTSQUERY_NEAR ) pNear = p;
       127567  +      if( p->bEof ) bTreeEof = 1;
126514 127568       }
126515 127569       if( bOr==0 ) return SQLITE_OK;
126516 127570   
126517 127571       /* This is the descendent of an OR node. In this case we cannot use
126518 127572       ** an incremental phrase. Load the entire doclist for the phrase
126519 127573       ** into memory in this case.  */
126520 127574       if( pPhrase->bIncr ){
................................................................................
126525 127579           fts3EvalNextRow(pCsr, pExpr, &rc);
126526 127580           if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
126527 127581         }
126528 127582         pIter = pPhrase->doclist.pList;
126529 127583         assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
126530 127584         if( rc!=SQLITE_OK ) return rc;
126531 127585       }
       127586  +    
       127587  +    iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
       127588  +    while( bTreeEof==1 
       127589  +        && pNear->bEof==0
       127590  +        && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
       127591  +    ){
       127592  +      int rc = SQLITE_OK;
       127593  +      fts3EvalNextRow(pCsr, pExpr, &rc);
       127594  +      if( rc!=SQLITE_OK ) return rc;
       127595  +      iDocid = pExpr->iDocid;
       127596  +      pIter = pPhrase->doclist.pList;
       127597  +    }
126532 127598   
126533         -    if( pExpr->bEof ){
126534         -      pIter = 0;
126535         -      iDocid = 0;
126536         -    }
126537 127599       bEof = (pPhrase->doclist.nAll==0);
126538 127600       assert( bDescDoclist==0 || bDescDoclist==1 );
126539 127601       assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
126540 127602   
126541         -    if( pCsr->bDesc==bDescDoclist ){
126542         -      int dummy;
126543         -      while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
126544         -        sqlite3Fts3DoclistPrev(
126545         -            bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
126546         -            &pIter, &iDocid, &dummy, &bEof
126547         -        );
126548         -      }
126549         -    }else{
126550         -      while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
126551         -        sqlite3Fts3DoclistNext(
126552         -            bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
126553         -            &pIter, &iDocid, &bEof
126554         -        );
       127603  +    if( bEof==0 ){
       127604  +      if( pCsr->bDesc==bDescDoclist ){
       127605  +        int dummy;
       127606  +        if( pNear->bEof ){
       127607  +          /* This expression is already at EOF. So position it to point to the
       127608  +          ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
       127609  +          ** iDocid is already set for this entry, so all that is required is
       127610  +          ** to set pIter to point to the first byte of the last position-list
       127611  +          ** in the doclist. 
       127612  +          **
       127613  +          ** It would also be correct to set pIter and iDocid to zero. In
       127614  +          ** this case, the first call to sqltie3Fts4DoclistPrev() below
       127615  +          ** would also move the iterator to point to the last entry in the 
       127616  +          ** doclist. However, this is expensive, as to do so it has to 
       127617  +          ** iterate through the entire doclist from start to finish (since
       127618  +          ** it does not know the docid for the last entry).  */
       127619  +          pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
       127620  +          fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
       127621  +        }
       127622  +        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
       127623  +          sqlite3Fts3DoclistPrev(
       127624  +              bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
       127625  +              &pIter, &iDocid, &dummy, &bEof
       127626  +          );
       127627  +        }
       127628  +      }else{
       127629  +        if( pNear->bEof ){
       127630  +          pIter = 0;
       127631  +          iDocid = 0;
       127632  +        }
       127633  +        while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
       127634  +          sqlite3Fts3DoclistNext(
       127635  +              bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
       127636  +              &pIter, &iDocid, &bEof
       127637  +          );
       127638  +        }
126555 127639         }
126556 127640       }
126557 127641   
126558 127642       if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
126559 127643     }
126560 127644     if( pIter==0 ) return SQLITE_OK;
126561 127645   
................................................................................
135385 136469     p->bAutoincrmerge = fts3Getint(&zParam)!=0;
135386 136470     if( !p->bHasStat ){
135387 136471       assert( p->bFts4==0 );
135388 136472       sqlite3Fts3CreateStatTable(&rc, p);
135389 136473       if( rc ) return rc;
135390 136474     }
135391 136475     rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
135392         -  if( rc ) return rc;;
       136476  +  if( rc ) return rc;
135393 136477     sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
135394 136478     sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
135395 136479     sqlite3_step(pStmt);
135396 136480     rc = sqlite3_reset(pStmt);
135397 136481     return rc;
135398 136482   }
135399 136483   
................................................................................
135654 136738       rc = fts3DoAutoincrmerge(p, &zVal[10]);
135655 136739   #ifdef SQLITE_TEST
135656 136740     }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
135657 136741       p->nNodeSize = atoi(&zVal[9]);
135658 136742       rc = SQLITE_OK;
135659 136743     }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
135660 136744       p->nMaxPendingData = atoi(&zVal[11]);
       136745  +    rc = SQLITE_OK;
       136746  +  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
       136747  +    p->bNoIncrDoclist = atoi(&zVal[21]);
135661 136748       rc = SQLITE_OK;
135662 136749   #endif
135663 136750     }else{
135664 136751       rc = SQLITE_ERROR;
135665 136752     }
135666 136753   
135667 136754     return rc;

Changes to SQLite.Interop/src/core/sqlite3.h.

   105    105   **
   106    106   ** See also: [sqlite3_libversion()],
   107    107   ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
   108    108   ** [sqlite_version()] and [sqlite_source_id()].
   109    109   */
   110    110   #define SQLITE_VERSION        "3.8.1"
   111    111   #define SQLITE_VERSION_NUMBER 3008001
   112         -#define SQLITE_SOURCE_ID      "2013-09-12 02:09:05 75a8a8c1b39725d36db627536d0c69401f8e0815"
          112  +#define SQLITE_SOURCE_ID      "2013-10-12 20:22:00 f0cf8c85dcbcc7778aed2816792c368d777f79cb"
   113    113   
   114    114   /*
   115    115   ** CAPI3REF: Run-Time Library Version Numbers
   116    116   ** KEYWORDS: sqlite3_version, sqlite3_sourceid
   117    117   **
   118    118   ** These interfaces provide the same information as the [SQLITE_VERSION],
   119    119   ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
................................................................................
  1613   1613   ** log message after formatting via [sqlite3_snprintf()].
  1614   1614   ** The SQLite logging interface is not reentrant; the logger function
  1615   1615   ** supplied by the application must not invoke any SQLite interface.
  1616   1616   ** In a multi-threaded application, the application-defined logger
  1617   1617   ** function must be threadsafe. </dd>
  1618   1618   **
  1619   1619   ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1620         -** <dd> This option takes a single argument of type int. If non-zero, then
         1620  +** <dd>^(This option takes a single argument of type int. If non-zero, then
  1621   1621   ** URI handling is globally enabled. If the parameter is zero, then URI handling
  1622         -** is globally disabled. If URI handling is globally enabled, all filenames
         1622  +** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  1623   1623   ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1624   1624   ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1625   1625   ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1626         -** connection is opened. If it is globally disabled, filenames are
         1626  +** connection is opened. ^If it is globally disabled, filenames are
  1627   1627   ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1628         -** database connection is opened. By default, URI handling is globally
         1628  +** database connection is opened. ^(By default, URI handling is globally
  1629   1629   ** disabled. The default value may be changed by compiling with the
  1630         -** [SQLITE_USE_URI] symbol defined.
         1630  +** [SQLITE_USE_URI] symbol defined.)^
  1631   1631   **
  1632   1632   ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1633         -** <dd> This option takes a single integer argument which is interpreted as
         1633  +** <dd>^This option takes a single integer argument which is interpreted as
  1634   1634   ** a boolean in order to enable or disable the use of covering indices for
  1635         -** full table scans in the query optimizer.  The default setting is determined
         1635  +** full table scans in the query optimizer.  ^The default setting is determined
  1636   1636   ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1637   1637   ** if that compile-time option is omitted.
  1638   1638   ** The ability to disable the use of covering indices for full table scans
  1639   1639   ** is because some incorrectly coded legacy applications might malfunction
  1640         -** malfunction when the optimization is enabled.  Providing the ability to
         1640  +** when the optimization is enabled.  Providing the ability to
  1641   1641   ** disable the optimization allows the older, buggy application code to work
  1642   1642   ** without change even with newer versions of SQLite.
  1643   1643   **
  1644   1644   ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1645   1645   ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1646   1646   ** <dd> These options are obsolete and should not be used by new code.
  1647   1647   ** They are retained for backwards compatibility but are now no-ops.
................................................................................
  1662   1662   ** the connection being passed as the second parameter is being closed. The
  1663   1663   ** third parameter is passed NULL In this case.  An example of using this
  1664   1664   ** configuration option can be seen in the "test_sqllog.c" source file in
  1665   1665   ** the canonical SQLite source tree.</dd>
  1666   1666   **
  1667   1667   ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1668   1668   ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1669         -** <dd>SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
         1669  +** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1670   1670   ** that are the default mmap size limit (the default setting for
  1671   1671   ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1672         -** The default setting can be overridden by each database connection using
         1672  +** ^The default setting can be overridden by each database connection using
  1673   1673   ** either the [PRAGMA mmap_size] command, or by using the
  1674         -** [SQLITE_FCNTL_MMAP_SIZE] file control.  The maximum allowed mmap size
         1674  +** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
  1675   1675   ** cannot be changed at run-time.  Nor may the maximum allowed mmap size
  1676   1676   ** exceed the compile-time maximum mmap size set by the
  1677         -** [SQLITE_MAX_MMAP_SIZE] compile-time option.  
  1678         -** If either argument to this option is negative, then that argument is
         1677  +** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
         1678  +** ^If either argument to this option is negative, then that argument is
  1679   1679   ** changed to its compile-time default.
  1680   1680   ** </dl>
  1681   1681   */
  1682   1682   #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
  1683   1683   #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
  1684   1684   #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
  1685   1685   #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */