/ Check-in [c78b0d30]
Login

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

Overview
Comment:Merge in the latest changes from trunk.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | uri-enhancement
Files: files | file ages | folders
SHA1: c78b0d302c6908ad5bf75a4f6fb77d1a0b3e8a76
User & Date: drh 2013-08-07 18:07:05
Context
2013-08-07
18:07
Merge in the latest changes from trunk. Closed-Leaf check-in: c78b0d30 user: drh tags: uri-enhancement
14:18
Add a guard #ifndef to test_intarray.h to prevent harm if it is #included more than once. Add a comment on the closing #endif of the guards on sqlite3.h and test_multiplex.h. check-in: 0ad83ceb user: drh tags: trunk
2013-07-24
14:54
Another attempt at generalizing the URI parsing so that it works with a wider variety of file URIs and yet remains backwards compatible. check-in: de05eb75 user: drh tags: uri-enhancement
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to Makefile.msc.

   468    468   NAWK = gawk.exe
   469    469   
   470    470   # You should not have to change anything below this line
   471    471   ###############################################################################
   472    472   
   473    473   # Object files for the SQLite library (non-amalgamation).
   474    474   #
   475         -LIBOBJS0 = alter.lo analyze.lo attach.lo auth.lo \
          475  +LIBOBJS0 = vdbe.lo parse.lo alter.lo analyze.lo attach.lo auth.lo \
   476    476            backup.lo bitvec.lo btmutex.lo btree.lo build.lo \
   477    477            callback.lo complete.lo ctime.lo date.lo delete.lo \
   478    478            expr.lo fault.lo fkey.lo \
   479    479            fts3.lo fts3_aux.lo fts3_expr.lo fts3_hash.lo fts3_icu.lo \
   480    480            fts3_porter.lo fts3_snippet.lo fts3_tokenizer.lo fts3_tokenizer1.lo \
   481    481            fts3_tokenize_vtab.lo fts3_unicode.lo fts3_unicode2.lo fts3_write.lo \
   482    482            func.lo global.lo hash.lo \
   483    483            icu.lo insert.lo journal.lo legacy.lo loadext.lo \
   484    484            main.lo malloc.lo mem0.lo mem1.lo mem2.lo mem3.lo mem5.lo \
   485    485            memjournal.lo \
   486    486            mutex.lo mutex_noop.lo mutex_unix.lo mutex_w32.lo \
   487    487            notify.lo opcodes.lo os.lo os_unix.lo os_win.lo \
   488         -         pager.lo parse.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \
          488  +         pager.lo pcache.lo pcache1.lo pragma.lo prepare.lo printf.lo \
   489    489            random.lo resolve.lo rowset.lo rtree.lo select.lo status.lo \
   490    490            table.lo tokenize.lo trigger.lo \
   491    491            update.lo util.lo vacuum.lo \
   492         -         vdbe.lo vdbeapi.lo vdbeaux.lo vdbeblob.lo vdbemem.lo vdbesort.lo \
          492  +         vdbeapi.lo vdbeaux.lo vdbeblob.lo vdbemem.lo vdbesort.lo \
   493    493            vdbetrace.lo wal.lo walker.lo where.lo utf.lo vtab.lo
   494    494   
   495    495   # Object files for the amalgamation.
   496    496   #
   497    497   LIBOBJS1 = sqlite3.lo
   498    498   
   499    499   # Determine the real value of LIBOBJ based on the 'configure' script

Changes to configure.

     1      1   #! /bin/sh
     2      2   # Guess values for system-dependent variables and create Makefiles.
     3         -# Generated by GNU Autoconf 2.62 for sqlite 3.7.17.
            3  +# Generated by GNU Autoconf 2.62 for sqlite 3.8.0.
     4      4   #
     5      5   # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
     6      6   # 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
     7      7   # This configure script is free software; the Free Software Foundation
     8      8   # gives unlimited permission to copy, distribute and modify it.
     9      9   ## --------------------- ##
    10     10   ## M4sh Initialization.  ##
................................................................................
   739    739   MFLAGS=
   740    740   MAKEFLAGS=
   741    741   SHELL=${CONFIG_SHELL-/bin/sh}
   742    742   
   743    743   # Identity of this package.
   744    744   PACKAGE_NAME='sqlite'
   745    745   PACKAGE_TARNAME='sqlite'
   746         -PACKAGE_VERSION='3.7.17'
   747         -PACKAGE_STRING='sqlite 3.7.17'
          746  +PACKAGE_VERSION='3.8.0'
          747  +PACKAGE_STRING='sqlite 3.8.0'
   748    748   PACKAGE_BUGREPORT=''
   749    749   
   750    750   # Factoring default headers for most tests.
   751    751   ac_includes_default="\
   752    752   #include <stdio.h>
   753    753   #ifdef HAVE_SYS_TYPES_H
   754    754   # include <sys/types.h>
................................................................................
  1480   1480   #
  1481   1481   # Report the --help message.
  1482   1482   #
  1483   1483   if test "$ac_init_help" = "long"; then
  1484   1484     # Omit some internal or obsolete options to make the list less imposing.
  1485   1485     # This message is too long to be a string in the A/UX 3.1 sh.
  1486   1486     cat <<_ACEOF
  1487         -\`configure' configures sqlite 3.7.17 to adapt to many kinds of systems.
         1487  +\`configure' configures sqlite 3.8.0 to adapt to many kinds of systems.
  1488   1488   
  1489   1489   Usage: $0 [OPTION]... [VAR=VALUE]...
  1490   1490   
  1491   1491   To assign environment variables (e.g., CC, CFLAGS...), specify them as
  1492   1492   VAR=VALUE.  See below for descriptions of some of the useful variables.
  1493   1493   
  1494   1494   Defaults for the options are specified in brackets.
................................................................................
  1545   1545     --build=BUILD     configure for building on BUILD [guessed]
  1546   1546     --host=HOST       cross-compile to build programs to run on HOST [BUILD]
  1547   1547   _ACEOF
  1548   1548   fi
  1549   1549   
  1550   1550   if test -n "$ac_init_help"; then
  1551   1551     case $ac_init_help in
  1552         -     short | recursive ) echo "Configuration of sqlite 3.7.17:";;
         1552  +     short | recursive ) echo "Configuration of sqlite 3.8.0:";;
  1553   1553      esac
  1554   1554     cat <<\_ACEOF
  1555   1555   
  1556   1556   Optional Features:
  1557   1557     --disable-option-checking  ignore unrecognized --enable/--with options
  1558   1558     --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
  1559   1559     --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
................................................................................
  1661   1661       cd "$ac_pwd" || { ac_status=$?; break; }
  1662   1662     done
  1663   1663   fi
  1664   1664   
  1665   1665   test -n "$ac_init_help" && exit $ac_status
  1666   1666   if $ac_init_version; then
  1667   1667     cat <<\_ACEOF
  1668         -sqlite configure 3.7.17
         1668  +sqlite configure 3.8.0
  1669   1669   generated by GNU Autoconf 2.62
  1670   1670   
  1671   1671   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
  1672   1672   2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
  1673   1673   This configure script is free software; the Free Software Foundation
  1674   1674   gives unlimited permission to copy, distribute and modify it.
  1675   1675   _ACEOF
  1676   1676     exit
  1677   1677   fi
  1678   1678   cat >config.log <<_ACEOF
  1679   1679   This file contains any messages produced by compilers while
  1680   1680   running configure, to aid debugging if configure makes a mistake.
  1681   1681   
  1682         -It was created by sqlite $as_me 3.7.17, which was
         1682  +It was created by sqlite $as_me 3.8.0, which was
  1683   1683   generated by GNU Autoconf 2.62.  Invocation command line was
  1684   1684   
  1685   1685     $ $0 $@
  1686   1686   
  1687   1687   _ACEOF
  1688   1688   exec 5>>config.log
  1689   1689   {
................................................................................
 14028  14028   
 14029  14029   exec 6>&1
 14030  14030   
 14031  14031   # Save the log message, to keep $[0] and so on meaningful, and to
 14032  14032   # report actual input values of CONFIG_FILES etc. instead of their
 14033  14033   # values after options handling.
 14034  14034   ac_log="
 14035         -This file was extended by sqlite $as_me 3.7.17, which was
        14035  +This file was extended by sqlite $as_me 3.8.0, which was
 14036  14036   generated by GNU Autoconf 2.62.  Invocation command line was
 14037  14037   
 14038  14038     CONFIG_FILES    = $CONFIG_FILES
 14039  14039     CONFIG_HEADERS  = $CONFIG_HEADERS
 14040  14040     CONFIG_LINKS    = $CONFIG_LINKS
 14041  14041     CONFIG_COMMANDS = $CONFIG_COMMANDS
 14042  14042     $ $0 $@
................................................................................
 14081  14081   $config_commands
 14082  14082   
 14083  14083   Report bugs to <bug-autoconf@gnu.org>."
 14084  14084   
 14085  14085   _ACEOF
 14086  14086   cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 14087  14087   ac_cs_version="\\
 14088         -sqlite config.status 3.7.17
        14088  +sqlite config.status 3.8.0
 14089  14089   configured by $0, generated by GNU Autoconf 2.62,
 14090  14090     with options \\"`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
 14091  14091   
 14092  14092   Copyright (C) 2008 Free Software Foundation, Inc.
 14093  14093   This config.status script is free software; the Free Software Foundation
 14094  14094   gives unlimited permission to copy, distribute and modify it."
 14095  14095   

Changes to ext/misc/vtshim.c.

   425    425   
   426    426   /* The destructor function for a disposible module */
   427    427   static void vtshimAuxDestructor(void *pXAux){
   428    428     vtshim_aux *pAux = (vtshim_aux*)pXAux;
   429    429     assert( pAux->pAllVtab==0 );
   430    430     if( !pAux->bDisposed && pAux->xChildDestroy ){
   431    431       pAux->xChildDestroy(pAux->pChildAux);
          432  +    pAux->xChildDestroy = 0;
   432    433     }
   433    434     sqlite3_free(pAux->zName);
   434    435     sqlite3_free(pAux->pMod);
   435    436     sqlite3_free(pAux);
   436    437   }
   437    438   
   438    439   static int vtshimCopyModule(
................................................................................
   523    524       for(pVtab=pAux->pAllVtab; pVtab; pVtab=pVtab->pNext){
   524    525         for(pCur=pVtab->pAllCur; pCur; pCur=pCur->pNext){
   525    526           pAux->pMod->xClose(pCur->pChild);
   526    527         }
   527    528         pAux->pMod->xDisconnect(pVtab->pChild);
   528    529       }
   529    530       pAux->bDisposed = 1;
   530         -    if( pAux->xChildDestroy ) pAux->xChildDestroy(pAux->pChildAux);
          531  +    if( pAux->xChildDestroy ){
          532  +      pAux->xChildDestroy(pAux->pChildAux);
          533  +      pAux->xChildDestroy = 0;
          534  +    }
   531    535     }
   532    536   }
   533    537   
   534    538   
   535    539   #endif /* SQLITE_OMIT_VIRTUALTABLE */
   536    540   
   537    541   #ifdef _WIN32

Changes to main.mk.

    46     46   #
    47     47   TCCX =  $(TCC) $(OPTS) -I. -I$(TOP)/src -I$(TOP) 
    48     48   TCCX += -I$(TOP)/ext/rtree -I$(TOP)/ext/icu -I$(TOP)/ext/fts3
    49     49   TCCX += -I$(TOP)/ext/async
    50     50   
    51     51   # Object files for the SQLite library.
    52     52   #
    53         -LIBOBJ+= alter.o analyze.o attach.o auth.o \
           53  +LIBOBJ+= vdbe.o parse.o \
           54  +         alter.o analyze.o attach.o auth.o \
    54     55            backup.o bitvec.o btmutex.o btree.o build.o \
    55     56            callback.o complete.o ctime.o date.o delete.o expr.o fault.o fkey.o \
    56     57            fts3.o fts3_aux.o fts3_expr.o fts3_hash.o fts3_icu.o fts3_porter.o \
    57     58            fts3_snippet.o fts3_tokenizer.o fts3_tokenizer1.o \
    58     59            fts3_tokenize_vtab.o \
    59     60   	 fts3_unicode.o fts3_unicode2.o \
    60     61            fts3_write.o func.o global.o hash.o \
    61     62            icu.o insert.o journal.o legacy.o loadext.o \
    62     63            main.o malloc.o mem0.o mem1.o mem2.o mem3.o mem5.o \
    63     64            memjournal.o \
    64     65            mutex.o mutex_noop.o mutex_unix.o mutex_w32.o \
    65     66            notify.o opcodes.o os.o os_unix.o os_win.o \
    66         -         pager.o parse.o pcache.o pcache1.o pragma.o prepare.o printf.o \
           67  +         pager.o pcache.o pcache1.o pragma.o prepare.o printf.o \
    67     68            random.o resolve.o rowset.o rtree.o select.o status.o \
    68     69            table.o tokenize.o trigger.o \
    69     70            update.o util.o vacuum.o \
    70         -         vdbe.o vdbeapi.o vdbeaux.o vdbeblob.o vdbemem.o vdbesort.o \
           71  +         vdbeapi.o vdbeaux.o vdbeblob.o vdbemem.o vdbesort.o \
    71     72   	 vdbetrace.o wal.o walker.o where.o utf.o vtab.o
    72     73   
    73     74   
    74     75   
    75     76   # All of the source code files.
    76     77   #
    77     78   SRC = \

Changes to mkopcodeh.awk.

    31     31   # properties apply to that opcode.  Set corresponding flags using the
    32     32   # OPFLG_INITIALIZER macro.
    33     33   #
    34     34   
    35     35   
    36     36   # Remember the TK_ values from the parse.h file
    37     37   /^#define TK_/ {
    38         -  tk[$2] = 0+$3
           38  +  tk[$2] = 0+$3    # tk[x] holds the numeric value for TK symbol X
    39     39   }
    40     40   
    41     41   # Scan for "case OP_aaaa:" lines in the vdbe.c file
    42     42   /^case OP_/ {
    43     43     name = $2
    44     44     sub(/:/,"",name)
    45     45     sub("\r","",name)
    46         -  op[name] = -1
           46  +  op[name] = -1       # op[x] holds the numeric value for OP symbol x
    47     47     jump[name] = 0
    48     48     out2_prerelease[name] = 0
    49     49     in1[name] = 0
    50     50     in2[name] = 0
    51     51     in3[name] = 0
    52     52     out2[name] = 0
    53     53     out3[name] = 0
    54     54     for(i=3; i<NF; i++){
    55     55       if($i=="same" && $(i+1)=="as"){
    56     56         sym = $(i+2)
    57     57         sub(/,/,"",sym)
    58         -      op[name] = tk[sym]
    59         -      used[op[name]] = 1
    60         -      sameas[op[name]] = sym
           58  +      val = tk[sym]
           59  +      op[name] = val
           60  +      used[val] = 1
           61  +      sameas[val] = sym
           62  +      def[val] = name
    61     63       }
    62     64       x = $i
    63     65       sub(",","",x)
    64     66       if(x=="jump"){
    65     67         jump[name] = 1
    66     68       }else if(x=="out2-prerelease"){
    67     69         out2_prerelease[name] = 1
................................................................................
    86     88     max = 0
    87     89     print "/* Automatically generated.  Do not edit */"
    88     90     print "/* See the mkopcodeh.awk script for details */"
    89     91     op["OP_Noop"] = -1;
    90     92     order[n_op++] = "OP_Noop";
    91     93     op["OP_Explain"] = -1;
    92     94     order[n_op++] = "OP_Explain";
           95  +
           96  +  # Assign small values to opcodes that are processed by resolveP2Values()
           97  +  # to make code generation for the switch() statement smaller and faster.
           98  +  for(i=0; i<n_op; i++){
           99  +    name = order[i];
          100  +    if( op[name]>=0 ) continue;
          101  +    if( name=="OP_Function"      \
          102  +     || name=="OP_AggStep"       \
          103  +     || name=="OP_Transaction"   \
          104  +     || name=="OP_AutoCommit"    \
          105  +     || name=="OP_Savepoint"     \
          106  +     || name=="OP_Checkpoint"    \
          107  +     || name=="OP_Vacuum"        \
          108  +     || name=="OP_JournalMode"   \
          109  +     || name=="OP_VUpdate"       \
          110  +     || name=="OP_VFilter"       \
          111  +     || name=="OP_Next"          \
          112  +     || name=="OP_SorterNext"    \
          113  +     || name=="OP_Prev"          \
          114  +    ){
          115  +      cnt++
          116  +      while( used[cnt] ) cnt++
          117  +      op[name] = cnt
          118  +      used[cnt] = 1
          119  +      def[cnt] = name
          120  +    }
          121  +  }
          122  +
          123  +  # Generate the numeric values for opcodes
    93    124     for(i=0; i<n_op; i++){
    94    125       name = order[i];
    95    126       if( op[name]<0 ){
    96    127         cnt++
    97    128         while( used[cnt] ) cnt++
    98    129         op[name] = cnt
          130  +      used[cnt] = 1
          131  +      def[cnt] = name
          132  +    }
          133  +  }
          134  +  max = cnt
          135  +  for(i=1; i<=max; i++){
          136  +    if( !used[i] ){
          137  +      def[i] = "OP_NotUsed_" i 
    99    138       }
   100         -    used[op[name]] = 1;
   101         -    if( op[name]>max ) max = op[name]
   102         -    printf "#define %-25s %15d", name, op[name]
   103         -    if( sameas[op[name]] ) {
   104         -      printf "   /* same as %-12s*/", sameas[op[name]]
          139  +    printf "#define %-25s %15d", def[i], i
          140  +    if( sameas[i] ){
          141  +      printf "   /* same as %-12s*/", sameas[i]
   105    142       } 
   106    143       printf "\n"
   107         -
   108         -  }
   109         -  seenUnused = 0;
   110         -  for(i=1; i<max; i++){
   111         -    if( !used[i] ){
   112         -      if( !seenUnused ){
   113         -        printf "\n/* The following opcode values are never used */\n"
   114         -        seenUnused = 1
   115         -      }
   116         -      printf "#define %-25s %15d\n", sprintf( "OP_NotUsed_%-3d", i ), i
   117         -    }
   118    144     }
   119    145   
   120    146     # Generate the bitvectors:
   121    147     #
   122    148     #  bit 0:     jump
   123    149     #  bit 1:     pushes a result onto stack
   124    150     #  bit 2:     output to p1.  release p1 before opcode runs
   125    151     #
   126         -  for(i=0; i<=max; i++) bv[i] = 0;
   127         -  for(i=0; i<n_op; i++){
   128         -    name = order[i];
   129         -    x = op[name]
          152  +  for(i=0; i<=max; i++){
          153  +    name = def[i]
   130    154       a0 = a1 = a2 = a3 = a4 = a5 = a6 = a7 = 0
   131         -    # a7 = a9 = a10 = a11 = a12 = a13 = a14 = a15 = 0
   132    155       if( jump[name] ) a0 = 1;
   133    156       if( out2_prerelease[name] ) a1 = 2;
   134    157       if( in1[name] ) a2 = 4;
   135    158       if( in2[name] ) a3 = 8;
   136    159       if( in3[name] ) a4 = 16;
   137    160       if( out2[name] ) a5 = 32;
   138    161       if( out3[name] ) a6 = 64;
   139         -    # bv[x] = a0+a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12+a13+a14+a15;
   140         -    bv[x] = a0+a1+a2+a3+a4+a5+a6+a7;
          162  +    bv[i] = a0+a1+a2+a3+a4+a5+a6+a7;
   141    163     }
   142    164     print "\n"
   143    165     print "/* Properties such as \"out2\" or \"jump\" that are specified in"
   144    166     print "** comments following the \"case\" for each opcode in the vdbe.c"
   145    167     print "** are encoded into bitvectors as follows:"
   146    168     print "*/"
   147    169     print "#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */"

Changes to src/analyze.c.

   437    437     int iIdxCur;                 /* Cursor open on index being analyzed */
   438    438     Vdbe *v;                     /* The virtual machine being built up */
   439    439     int i;                       /* Loop counter */
   440    440     int topOfLoop;               /* The top of the loop */
   441    441     int endOfLoop;               /* The end of the loop */
   442    442     int jZeroRows = -1;          /* Jump from here if number of rows is zero */
   443    443     int iDb;                     /* Index of database containing pTab */
          444  +  u8 needTableCnt = 1;         /* True to count the table */
   444    445     int regTabname = iMem++;     /* Register containing table name */
   445    446     int regIdxname = iMem++;     /* Register containing index name */
   446    447     int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
   447    448   #ifdef SQLITE_ENABLE_STAT3
   448    449     int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
   449    450     int regNumLt = iMem++;       /* Number of keys less than regSample */
   450    451     int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
................................................................................
   496    497     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
   497    498       int nCol;
   498    499       KeyInfo *pKey;
   499    500       int addrIfNot = 0;           /* address of OP_IfNot */
   500    501       int *aChngAddr;              /* Array of jump instruction addresses */
   501    502   
   502    503       if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
          504  +    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
   503    505       VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
   504    506       nCol = pIdx->nColumn;
   505    507       aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
   506    508       if( aChngAddr==0 ) continue;
   507    509       pKey = sqlite3IndexKeyinfo(pParse, pIdx);
   508    510       if( iMem+1+(nCol*2)>pParse->nMem ){
   509    511         pParse->nMem = iMem+1+(nCol*2);
................................................................................
   655    657       **        I = (K+D-1)/D
   656    658       **
   657    659       ** If K==0 then no entry is made into the sqlite_stat1 table.  
   658    660       ** If K>0 then it is always the case the D>0 so division by zero
   659    661       ** is never possible.
   660    662       */
   661    663       sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
   662         -    if( jZeroRows<0 ){
   663         -      jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
   664         -    }
          664  +    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
   665    665       for(i=0; i<nCol; i++){
   666    666         sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
   667    667         sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
   668    668         sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
   669    669         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
   670    670         sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
   671    671         sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
   672    672         sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
   673    673       }
          674  +    if( pIdx->pPartIdxWhere!=0 ) sqlite3VdbeJumpHere(v, jZeroRows);
   674    675       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   675    676       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   676    677       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
   677    678       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
          679  +    if( pIdx->pPartIdxWhere==0 ) sqlite3VdbeJumpHere(v, jZeroRows);
   678    680     }
   679    681   
   680         -  /* If the table has no indices, create a single sqlite_stat1 entry
   681         -  ** containing NULL as the index name and the row count as the content.
          682  +  /* Create a single sqlite_stat1 entry containing NULL as the index
          683  +  ** name and the row count as the content.
   682    684     */
   683         -  if( pTab->pIndex==0 ){
          685  +  if( pOnlyIdx==0 && needTableCnt ){
   684    686       sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
   685    687       VdbeComment((v, "%s", pTab->zName));
   686    688       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
   687    689       sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
   688    690       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
   689         -  }else{
          691  +    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
          692  +    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
          693  +    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
          694  +    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
          695  +    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   690    696       sqlite3VdbeJumpHere(v, jZeroRows);
   691         -    jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
   692    697     }
   693         -  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
   694         -  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
   695         -  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
   696         -  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
   697         -  sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
   698    698     if( pParse->nMem<regRec ) pParse->nMem = regRec;
   699         -  sqlite3VdbeJumpHere(v, jZeroRows);
   700    699   }
   701    700   
   702    701   
   703    702   /*
   704    703   ** Generate code that will cause the most recent index analysis to
   705    704   ** be loaded into internal hash tables where is can be used.
   706    705   */
................................................................................
   875    874     z = argv[2];
   876    875     for(i=0; *z && i<=n; i++){
   877    876       v = 0;
   878    877       while( (c=z[0])>='0' && c<='9' ){
   879    878         v = v*10 + c - '0';
   880    879         z++;
   881    880       }
   882         -    if( i==0 ) pTable->nRowEst = v;
   883         -    if( pIndex==0 ) break;
          881  +    if( i==0 && (pIndex==0 || pIndex->pPartIdxWhere==0) ){
          882  +      if( v>0 ) pTable->nRowEst = v;
          883  +      if( pIndex==0 ) break;
          884  +    }
   884    885       pIndex->aiRowEst[i] = v;
   885    886       if( *z==' ' ) z++;
   886    887       if( strcmp(z, "unordered")==0 ){
   887    888         pIndex->bUnordered = 1;
   888    889         break;
   889    890       }
   890    891     }

Changes to src/build.c.

   378    378   /*
   379    379   ** Reclaim the memory used by an index
   380    380   */
   381    381   static void freeIndex(sqlite3 *db, Index *p){
   382    382   #ifndef SQLITE_OMIT_ANALYZE
   383    383     sqlite3DeleteIndexSamples(db, p);
   384    384   #endif
          385  +  sqlite3ExprDelete(db, p->pPartIdxWhere);
   385    386     sqlite3DbFree(db, p->zColAff);
   386    387     sqlite3DbFree(db, p);
   387    388   }
   388    389   
   389    390   /*
   390    391   ** For the index called zIdxName which is found in the database iDb,
   391    392   ** unlike that index from its Table then remove the index from
................................................................................
  1221   1222     }else if( autoInc ){
  1222   1223   #ifndef SQLITE_OMIT_AUTOINCREMENT
  1223   1224       sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  1224   1225          "INTEGER PRIMARY KEY");
  1225   1226   #endif
  1226   1227     }else{
  1227   1228       Index *p;
  1228         -    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
         1229  +    p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
         1230  +                           0, sortOrder, 0);
  1229   1231       if( p ){
  1230   1232         p->autoIndex = 2;
  1231   1233       }
  1232   1234       pList = 0;
  1233   1235     }
  1234   1236   
  1235   1237   primary_key_exit:
................................................................................
  1516   1518   
  1517   1519     iDb = sqlite3SchemaToIndex(db, p->pSchema);
  1518   1520   
  1519   1521   #ifndef SQLITE_OMIT_CHECK
  1520   1522     /* Resolve names in all CHECK constraint expressions.
  1521   1523     */
  1522   1524     if( p->pCheck ){
  1523         -    SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
  1524         -    NameContext sNC;                /* Name context for pParse->pNewTable */
  1525         -    ExprList *pList;                /* List of all CHECK constraints */
  1526         -    int i;                          /* Loop counter */
  1527         -
  1528         -    memset(&sNC, 0, sizeof(sNC));
  1529         -    memset(&sSrc, 0, sizeof(sSrc));
  1530         -    sSrc.nSrc = 1;
  1531         -    sSrc.a[0].zName = p->zName;
  1532         -    sSrc.a[0].pTab = p;
  1533         -    sSrc.a[0].iCursor = -1;
  1534         -    sNC.pParse = pParse;
  1535         -    sNC.pSrcList = &sSrc;
  1536         -    sNC.ncFlags = NC_IsCheck;
  1537         -    pList = p->pCheck;
  1538         -    for(i=0; i<pList->nExpr; i++){
  1539         -      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  1540         -        return;
  1541         -      }
  1542         -    }
         1525  +    sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  1543   1526     }
  1544   1527   #endif /* !defined(SQLITE_OMIT_CHECK) */
  1545   1528   
  1546   1529     /* If the db->init.busy is 1 it means we are reading the SQL off the
  1547   1530     ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  1548   1531     ** So do not write to the disk again.  Extract the root page number
  1549   1532     ** for the table from the db->init.newTnum field.  (The page number
................................................................................
  2387   2370     Table *pTab = pIndex->pTable;  /* The table that is indexed */
  2388   2371     int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
  2389   2372     int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
  2390   2373     int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
  2391   2374     int addr1;                     /* Address of top of loop */
  2392   2375     int addr2;                     /* Address to jump to for next iteration */
  2393   2376     int tnum;                      /* Root page of index */
         2377  +  int iPartIdxLabel;             /* Jump to this label to skip a row */
  2394   2378     Vdbe *v;                       /* Generate code into this virtual machine */
  2395   2379     KeyInfo *pKey;                 /* KeyInfo for index */
  2396   2380     int regRecord;                 /* Register holding assemblied index record */
  2397   2381     sqlite3 *db = pParse->db;      /* The database connection */
  2398   2382     int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  2399   2383   
  2400   2384   #ifndef SQLITE_OMIT_AUTHORIZATION
................................................................................
  2426   2410   
  2427   2411     /* Open the table. Loop through all rows of the table, inserting index
  2428   2412     ** records into the sorter. */
  2429   2413     sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  2430   2414     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  2431   2415     regRecord = sqlite3GetTempReg(pParse);
  2432   2416   
  2433         -  sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
         2417  +  sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
  2434   2418     sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
         2419  +  sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  2435   2420     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  2436   2421     sqlite3VdbeJumpHere(v, addr1);
  2437   2422     addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  2438   2423     if( pIndex->onError!=OE_None ){
  2439   2424       int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  2440   2425       sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  2441   2426       addr2 = sqlite3VdbeCurrentAddr(v);
................................................................................
  2478   2463     Parse *pParse,     /* All information about this parse */
  2479   2464     Token *pName1,     /* First part of index name. May be NULL */
  2480   2465     Token *pName2,     /* Second part of index name. May be NULL */
  2481   2466     SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  2482   2467     ExprList *pList,   /* A list of columns to be indexed */
  2483   2468     int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  2484   2469     Token *pStart,     /* The CREATE token that begins this statement */
  2485         -  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
         2470  +  Expr *pPIWhere,    /* WHERE clause for partial indices */
  2486   2471     int sortOrder,     /* Sort order of primary key when pList==NULL */
  2487   2472     int ifNotExist     /* Omit error if index already exists */
  2488   2473   ){
  2489   2474     Index *pRet = 0;     /* Pointer to return */
  2490   2475     Table *pTab = 0;     /* Table to be indexed */
  2491   2476     Index *pIndex = 0;   /* The index to be created */
  2492   2477     char *zName = 0;     /* Name of the index */
................................................................................
  2500   2485     int iDb;             /* Index of the database that is being written */
  2501   2486     Token *pName = 0;    /* Unqualified name of the index to create */
  2502   2487     struct ExprList_item *pListItem; /* For looping over pList */
  2503   2488     int nCol;
  2504   2489     int nExtra = 0;
  2505   2490     char *zExtra;
  2506   2491   
  2507         -  assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
  2508   2492     assert( pParse->nErr==0 );      /* Never called with prior errors */
  2509   2493     if( db->mallocFailed || IN_DECLARE_VTAB ){
  2510   2494       goto exit_create_index;
  2511   2495     }
  2512   2496     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  2513   2497       goto exit_create_index;
  2514   2498     }
................................................................................
  2546   2530         /* Because the parser constructs pTblName from a single identifier,
  2547   2531         ** sqlite3FixSrcList can never fail. */
  2548   2532         assert(0);
  2549   2533       }
  2550   2534       pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  2551   2535       assert( db->mallocFailed==0 || pTab==0 );
  2552   2536       if( pTab==0 ) goto exit_create_index;
  2553         -    assert( db->aDb[iDb].pSchema==pTab->pSchema );
         2537  +    if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
         2538  +      sqlite3ErrorMsg(pParse, 
         2539  +           "cannot create a TEMP index on non-TEMP table \"%s\"",
         2540  +           pTab->zName);
         2541  +      goto exit_create_index;
         2542  +    }
  2554   2543     }else{
  2555   2544       assert( pName==0 );
  2556   2545       assert( pStart==0 );
  2557   2546       pTab = pParse->pNewTable;
  2558   2547       if( !pTab ) goto exit_create_index;
  2559   2548       iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  2560   2549     }
................................................................................
  2695   2684     memcpy(pIndex->zName, zName, nName+1);
  2696   2685     pIndex->pTable = pTab;
  2697   2686     pIndex->nColumn = pList->nExpr;
  2698   2687     pIndex->onError = (u8)onError;
  2699   2688     pIndex->uniqNotNull = onError==OE_Abort;
  2700   2689     pIndex->autoIndex = (u8)(pName==0);
  2701   2690     pIndex->pSchema = db->aDb[iDb].pSchema;
         2691  +  if( pPIWhere ){
         2692  +    sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
         2693  +    pIndex->pPartIdxWhere = pPIWhere;
         2694  +    pPIWhere = 0;
         2695  +  }
  2702   2696     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  2703   2697   
  2704   2698     /* Check to see if we should honor DESC requests on index columns
  2705   2699     */
  2706   2700     if( pDb->pSchema->file_format>=4 ){
  2707   2701       sortOrderMask = -1;   /* Honor DESC */
  2708   2702     }else{
................................................................................
  2850   2844     ** we don't want to recreate it.
  2851   2845     **
  2852   2846     ** If pTblName==0 it means this index is generated as a primary key
  2853   2847     ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
  2854   2848     ** has just been created, it contains no data and the index initialization
  2855   2849     ** step can be skipped.
  2856   2850     */
  2857         -  else{ /* if( db->init.busy==0 ) */
         2851  +  else if( pParse->nErr==0 ){
  2858   2852       Vdbe *v;
  2859   2853       char *zStmt;
  2860   2854       int iMem = ++pParse->nMem;
  2861   2855   
  2862   2856       v = sqlite3GetVdbe(pParse);
  2863   2857       if( v==0 ) goto exit_create_index;
  2864   2858   
................................................................................
  2868   2862       sqlite3BeginWriteOperation(pParse, 1, iDb);
  2869   2863       sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  2870   2864   
  2871   2865       /* Gather the complete text of the CREATE INDEX statement into
  2872   2866       ** the zStmt variable
  2873   2867       */
  2874   2868       if( pStart ){
  2875         -      assert( pEnd!=0 );
         2869  +      int n = (pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
         2870  +      if( pName->z[n-1]==';' ) n--;
  2876   2871         /* A named index with an explicit CREATE INDEX statement */
  2877   2872         zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  2878         -        onError==OE_None ? "" : " UNIQUE",
  2879         -        (int)(pEnd->z - pName->z) + 1,
  2880         -        pName->z);
         2873  +        onError==OE_None ? "" : " UNIQUE", n, pName->z);
  2881   2874       }else{
  2882   2875         /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  2883   2876         /* zStmt = sqlite3MPrintf(""); */
  2884   2877         zStmt = 0;
  2885   2878       }
  2886   2879   
  2887   2880       /* Add an entry in sqlite_master for this index
................................................................................
  2929   2922       }
  2930   2923       pRet = pIndex;
  2931   2924       pIndex = 0;
  2932   2925     }
  2933   2926   
  2934   2927     /* Clean up before exiting */
  2935   2928   exit_create_index:
  2936         -  if( pIndex ){
  2937         -    sqlite3DbFree(db, pIndex->zColAff);
  2938         -    sqlite3DbFree(db, pIndex);
  2939         -  }
         2929  +  if( pIndex ) freeIndex(db, pIndex);
         2930  +  sqlite3ExprDelete(db, pPIWhere);
  2940   2931     sqlite3ExprListDelete(db, pList);
  2941   2932     sqlite3SrcListDelete(db, pTblName);
  2942   2933     sqlite3DbFree(db, zName);
  2943   2934     return pRet;
  2944   2935   }
  2945   2936   
  2946   2937   /*
................................................................................
  3810   3801   ** pointer. If an error occurs (out of memory or missing collation 
  3811   3802   ** sequence), NULL is returned and the state of pParse updated to reflect
  3812   3803   ** the error.
  3813   3804   */
  3814   3805   KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  3815   3806     int i;
  3816   3807     int nCol = pIdx->nColumn;
  3817         -  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  3818         -  sqlite3 *db = pParse->db;
  3819         -  KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
         3808  +  KeyInfo *pKey;
  3820   3809   
         3810  +  pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
  3821   3811     if( pKey ){
  3822         -    pKey->db = pParse->db;
  3823         -    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
  3824         -    assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
  3825   3812       for(i=0; i<nCol; i++){
  3826   3813         char *zColl = pIdx->azColl[i];
  3827   3814         assert( zColl );
  3828   3815         pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  3829   3816         pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  3830   3817       }
  3831         -    pKey->nField = (u16)nCol;
  3832   3818     }
  3833   3819   
  3834   3820     if( pParse->nErr ){
  3835         -    sqlite3DbFree(db, pKey);
         3821  +    sqlite3DbFree(pParse->db, pKey);
  3836   3822       pKey = 0;
  3837   3823     }
  3838   3824     return pKey;
  3839   3825   }

Changes to src/delete.c.

   587    587     Table *pTab,       /* Table containing the row to be deleted */
   588    588     int iCur,          /* Cursor number for the table */
   589    589     int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
   590    590   ){
   591    591     int i;
   592    592     Index *pIdx;
   593    593     int r1;
          594  +  int iPartIdxLabel;
          595  +  Vdbe *v = pParse->pVdbe;
   594    596   
   595    597     for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
   596    598       if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
   597         -    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
   598         -    sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
          599  +    r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel);
          600  +    sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1);
          601  +    sqlite3VdbeResolveLabel(v, iPartIdxLabel);
   599    602     }
   600    603   }
   601    604   
   602    605   /*
   603    606   ** Generate code that will assemble an index key and put it in register
   604    607   ** regOut.  The key with be for index pIdx which is an index on pTab.
   605    608   ** iCur is the index of a cursor open on the pTab table and pointing to
   606    609   ** the entry that needs indexing.
   607    610   **
   608    611   ** Return a register number which is the first in a block of
   609    612   ** registers that holds the elements of the index key.  The
   610    613   ** block of registers has already been deallocated by the time
   611    614   ** this routine returns.
          615  +**
          616  +** If *piPartIdxLabel is not NULL, fill it in with a label and jump
          617  +** to that label if pIdx is a partial index that should be skipped.
          618  +** A partial index should be skipped if its WHERE clause evaluates
          619  +** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
          620  +** will be set to zero which is an empty label that is ignored by
          621  +** sqlite3VdbeResolveLabel().
   612    622   */
   613    623   int sqlite3GenerateIndexKey(
   614         -  Parse *pParse,     /* Parsing context */
   615         -  Index *pIdx,       /* The index for which to generate a key */
   616         -  int iCur,          /* Cursor number for the pIdx->pTable table */
   617         -  int regOut,        /* Write the new index key to this register */
   618         -  int doMakeRec      /* Run the OP_MakeRecord instruction if true */
          624  +  Parse *pParse,       /* Parsing context */
          625  +  Index *pIdx,         /* The index for which to generate a key */
          626  +  int iCur,            /* Cursor number for the pIdx->pTable table */
          627  +  int regOut,          /* Write the new index key to this register */
          628  +  int doMakeRec,       /* Run the OP_MakeRecord instruction if true */
          629  +  int *piPartIdxLabel  /* OUT: Jump to this label to skip partial index */
   619    630   ){
   620    631     Vdbe *v = pParse->pVdbe;
   621    632     int j;
   622    633     Table *pTab = pIdx->pTable;
   623    634     int regBase;
   624    635     int nCol;
   625    636   
          637  +  if( piPartIdxLabel ){
          638  +    if( pIdx->pPartIdxWhere ){
          639  +      *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
          640  +      pParse->iPartIdxTab = iCur;
          641  +      sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 
          642  +                         SQLITE_JUMPIFNULL);
          643  +    }else{
          644  +      *piPartIdxLabel = 0;
          645  +    }
          646  +  }
   626    647     nCol = pIdx->nColumn;
   627    648     regBase = sqlite3GetTempRange(pParse, nCol+1);
   628    649     sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
   629    650     for(j=0; j<nCol; j++){
   630    651       int idx = pIdx->aiColumn[j];
   631    652       if( idx==pTab->iPKey ){
   632    653         sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);

Changes to src/expr.c.

  1688   1688       sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  1689   1689     }
  1690   1690   #endif
  1691   1691   
  1692   1692     switch( pExpr->op ){
  1693   1693       case TK_IN: {
  1694   1694         char affinity;              /* Affinity of the LHS of the IN */
  1695         -      KeyInfo keyInfo;            /* Keyinfo for the generated table */
  1696         -      static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
  1697   1695         int addr;                   /* Address of OP_OpenEphemeral instruction */
  1698   1696         Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
         1697  +      KeyInfo *pKeyInfo = 0;      /* Key information */
  1699   1698   
  1700   1699         if( rMayHaveNull ){
  1701   1700           sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  1702   1701         }
  1703   1702   
  1704   1703         affinity = sqlite3ExprAffinity(pLeft);
  1705   1704   
................................................................................
  1715   1714         ** if either column has NUMERIC or INTEGER affinity. If neither
  1716   1715         ** 'x' nor the SELECT... statement are columns, then numeric affinity
  1717   1716         ** is used.
  1718   1717         */
  1719   1718         pExpr->iTable = pParse->nTab++;
  1720   1719         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  1721   1720         if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  1722         -      memset(&keyInfo, 0, sizeof(keyInfo));
  1723         -      keyInfo.nField = 1;
  1724         -      keyInfo.aSortOrder = &sortOrder;
         1721  +      pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1);
  1725   1722   
  1726   1723         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  1727   1724           /* Case 1:     expr IN (SELECT ...)
  1728   1725           **
  1729   1726           ** Generate code to write the results of the select into the temporary
  1730   1727           ** table allocated and opened above.
  1731   1728           */
................................................................................
  1733   1730           ExprList *pEList;
  1734   1731   
  1735   1732           assert( !isRowid );
  1736   1733           sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  1737   1734           dest.affSdst = (u8)affinity;
  1738   1735           assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  1739   1736           pExpr->x.pSelect->iLimit = 0;
         1737  +        testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  1740   1738           if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
         1739  +          sqlite3DbFree(pParse->db, pKeyInfo);
  1741   1740             return 0;
  1742   1741           }
  1743   1742           pEList = pExpr->x.pSelect->pEList;
  1744         -        if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
  1745         -          keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  1746         -              pEList->a[0].pExpr);
  1747         -        }
         1743  +        assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
         1744  +        assert( pEList!=0 );
         1745  +        assert( pEList->nExpr>0 );
         1746  +        pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
         1747  +                                                         pEList->a[0].pExpr);
  1748   1748         }else if( ALWAYS(pExpr->x.pList!=0) ){
  1749   1749           /* Case 2:     expr IN (exprlist)
  1750   1750           **
  1751   1751           ** For each expression, build an index key from the evaluation and
  1752   1752           ** store it in the temporary table. If <expr> is a column, then use
  1753   1753           ** that columns affinity when building index keys. If <expr> is not
  1754   1754           ** a column, use numeric affinity.
................................................................................
  1757   1757           ExprList *pList = pExpr->x.pList;
  1758   1758           struct ExprList_item *pItem;
  1759   1759           int r1, r2, r3;
  1760   1760   
  1761   1761           if( !affinity ){
  1762   1762             affinity = SQLITE_AFF_NONE;
  1763   1763           }
  1764         -        keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  1765         -        keyInfo.aSortOrder = &sortOrder;
         1764  +        if( pKeyInfo ){
         1765  +          pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
         1766  +        }
  1766   1767   
  1767   1768           /* Loop through each expression in <exprlist>. */
  1768   1769           r1 = sqlite3GetTempReg(pParse);
  1769   1770           r2 = sqlite3GetTempReg(pParse);
  1770   1771           sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  1771   1772           for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  1772   1773             Expr *pE2 = pItem->pExpr;
................................................................................
  1797   1798                 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  1798   1799               }
  1799   1800             }
  1800   1801           }
  1801   1802           sqlite3ReleaseTempReg(pParse, r1);
  1802   1803           sqlite3ReleaseTempReg(pParse, r2);
  1803   1804         }
  1804         -      if( !isRowid ){
  1805         -        sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
         1805  +      if( pKeyInfo ){
         1806  +        sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF);
  1806   1807         }
  1807   1808         break;
  1808   1809       }
  1809   1810   
  1810   1811       case TK_EXISTS:
  1811   1812       case TK_SELECT:
  1812   1813       default: {
................................................................................
  2358   2359           sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  2359   2360                                 pCol->iSorterColumn, target);
  2360   2361           break;
  2361   2362         }
  2362   2363         /* Otherwise, fall thru into the TK_COLUMN case */
  2363   2364       }
  2364   2365       case TK_COLUMN: {
  2365         -      if( pExpr->iTable<0 ){
  2366         -        /* This only happens when coding check constraints */
  2367         -        assert( pParse->ckBase>0 );
  2368         -        inReg = pExpr->iColumn + pParse->ckBase;
  2369         -      }else{
  2370         -        inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  2371         -                                 pExpr->iColumn, pExpr->iTable, target,
  2372         -                                 pExpr->op2);
         2366  +      int iTab = pExpr->iTable;
         2367  +      if( iTab<0 ){
         2368  +        if( pParse->ckBase>0 ){
         2369  +          /* Generating CHECK constraints or inserting into partial index */
         2370  +          inReg = pExpr->iColumn + pParse->ckBase;
         2371  +          break;
         2372  +        }else{
         2373  +          /* Deleting from a partial index */
         2374  +          iTab = pParse->iPartIdxTab;
         2375  +        }
  2373   2376         }
         2377  +      inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
         2378  +                               pExpr->iColumn, iTab, target,
         2379  +                               pExpr->op2);
  2374   2380         break;
  2375   2381       }
  2376   2382       case TK_INTEGER: {
  2377   2383         codeInteger(pParse, pExpr, 0, target);
  2378   2384         break;
  2379   2385       }
  2380   2386   #ifndef SQLITE_OMIT_FLOATING_POINT
................................................................................
  3789   3795   
  3790   3796   /*
  3791   3797   ** Do a deep comparison of two expression trees.  Return 0 if the two
  3792   3798   ** expressions are completely identical.  Return 1 if they differ only
  3793   3799   ** by a COLLATE operator at the top level.  Return 2 if there are differences
  3794   3800   ** other than the top-level COLLATE operator.
  3795   3801   **
         3802  +** If any subelement of pB has Expr.iTable==(-1) then it is allowed
         3803  +** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
         3804  +**
         3805  +** The pA side might be using TK_REGISTER.  If that is the case and pB is
         3806  +** not using TK_REGISTER but is otherwise equivalent, then still return 0.
         3807  +**
  3796   3808   ** Sometimes this routine will return 2 even if the two expressions
  3797   3809   ** really are equivalent.  If we cannot prove that the expressions are
  3798   3810   ** identical, we return 2 just to be safe.  So if this routine
  3799   3811   ** returns 2, then you do not really know for certain if the two
  3800   3812   ** expressions are the same.  But if you get a 0 or 1 return, then you
  3801   3813   ** can be sure the expressions are the same.  In the places where
  3802   3814   ** this routine is used, it does not hurt to get an extra 2 - that
  3803   3815   ** just might result in some slightly slower code.  But returning
  3804   3816   ** an incorrect 0 or 1 could lead to a malfunction.
  3805   3817   */
  3806         -int sqlite3ExprCompare(Expr *pA, Expr *pB){
         3818  +int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  3807   3819     if( pA==0||pB==0 ){
  3808   3820       return pB==pA ? 0 : 2;
  3809   3821     }
  3810   3822     assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
  3811   3823     assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
  3812   3824     if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  3813   3825       return 2;
  3814   3826     }
  3815   3827     if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  3816         -  if( pA->op!=pB->op ){
  3817         -    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
         3828  +  if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
         3829  +    if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  3818   3830         return 1;
  3819   3831       }
  3820         -    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
         3832  +    if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  3821   3833         return 1;
  3822   3834       }
  3823   3835       return 2;
  3824   3836     }
  3825         -  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
  3826         -  if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
  3827         -  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
  3828         -  if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
         3837  +  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
         3838  +  if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
         3839  +  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
         3840  +  if( pA->iColumn!=pB->iColumn ) return 2;
         3841  +  if( pA->iTable!=pB->iTable 
         3842  +   && pA->op!=TK_REGISTER
         3843  +   && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  3829   3844     if( ExprHasProperty(pA, EP_IntValue) ){
  3830   3845       if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  3831   3846         return 2;
  3832   3847       }
  3833   3848     }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  3834   3849       if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  3835   3850       if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
................................................................................
  3839   3854     return 0;
  3840   3855   }
  3841   3856   
  3842   3857   /*
  3843   3858   ** Compare two ExprList objects.  Return 0 if they are identical and 
  3844   3859   ** non-zero if they differ in any way.
  3845   3860   **
         3861  +** If any subelement of pB has Expr.iTable==(-1) then it is allowed
         3862  +** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
         3863  +**
  3846   3864   ** This routine might return non-zero for equivalent ExprLists.  The
  3847   3865   ** only consequence will be disabled optimizations.  But this routine
  3848   3866   ** must never return 0 if the two ExprList objects are different, or
  3849   3867   ** a malfunction will result.
  3850   3868   **
  3851   3869   ** Two NULL pointers are considered to be the same.  But a NULL pointer
  3852   3870   ** always differs from a non-NULL pointer.
  3853   3871   */
  3854         -int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
         3872  +int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  3855   3873     int i;
  3856   3874     if( pA==0 && pB==0 ) return 0;
  3857   3875     if( pA==0 || pB==0 ) return 1;
  3858   3876     if( pA->nExpr!=pB->nExpr ) return 1;
  3859   3877     for(i=0; i<pA->nExpr; i++){
  3860   3878       Expr *pExprA = pA->a[i].pExpr;
  3861   3879       Expr *pExprB = pB->a[i].pExpr;
  3862   3880       if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  3863         -    if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
         3881  +    if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
         3882  +  }
         3883  +  return 0;
         3884  +}
         3885  +
         3886  +/*
         3887  +** Return true if we can prove the pE2 will always be true if pE1 is
         3888  +** true.  Return false if we cannot complete the proof or if pE2 might
         3889  +** be false.  Examples:
         3890  +**
         3891  +**     pE1: x==5       pE2: x==5             Result: true
         3892  +**     pE1: x>0        pE2: x==5             Result: false
         3893  +**     pE1: x=21       pE2: x=21 OR y=43     Result: true
         3894  +**     pE1: x!=123     pE2: x IS NOT NULL    Result: true
         3895  +**     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
         3896  +**     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
         3897  +**     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
         3898  +**
         3899  +** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
         3900  +** Expr.iTable<0 then assume a table number given by iTab.
         3901  +**
         3902  +** When in doubt, return false.  Returning true might give a performance
         3903  +** improvement.  Returning false might cause a performance reduction, but
         3904  +** it will always give the correct answer and is hence always safe.
         3905  +*/
         3906  +int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
         3907  +  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
         3908  +    return 1;
         3909  +  }
         3910  +  if( pE2->op==TK_OR
         3911  +   && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
         3912  +             || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
         3913  +  ){
         3914  +    return 1;
         3915  +  }
         3916  +  if( pE2->op==TK_NOTNULL
         3917  +   && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
         3918  +   && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
         3919  +  ){
         3920  +    return 1;
  3864   3921     }
  3865   3922     return 0;
  3866   3923   }
  3867   3924   
  3868   3925   /*
  3869   3926   ** An instance of the following structure is used by the tree walker
  3870   3927   ** to count references to table columns in the arguments of an 
................................................................................
  4041   4098          && pWalker->walkerDepth==pExpr->op2
  4042   4099         ){
  4043   4100           /* Check to see if pExpr is a duplicate of another aggregate 
  4044   4101           ** function that is already in the pAggInfo structure
  4045   4102           */
  4046   4103           struct AggInfo_func *pItem = pAggInfo->aFunc;
  4047   4104           for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  4048         -          if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
         4105  +          if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  4049   4106               break;
  4050   4107             }
  4051   4108           }
  4052   4109           if( i>=pAggInfo->nFunc ){
  4053   4110             /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
  4054   4111             */
  4055   4112             u8 enc = ENC(pParse->db);

Changes to src/insert.c.

  1375   1375     /* Test all UNIQUE constraints by creating entries for each UNIQUE
  1376   1376     ** index and making sure that duplicate entries do not already exist.
  1377   1377     ** Add the new records to the indices as we go.
  1378   1378     */
  1379   1379     for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  1380   1380       int regIdx;
  1381   1381       int regR;
         1382  +    int addrSkipRow = 0;
  1382   1383   
  1383   1384       if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
         1385  +
         1386  +    if( pIdx->pPartIdxWhere ){
         1387  +      sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
         1388  +      addrSkipRow = sqlite3VdbeMakeLabel(v);
         1389  +      pParse->ckBase = regData;
         1390  +      sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
         1391  +                         SQLITE_JUMPIFNULL);
         1392  +      pParse->ckBase = 0;
         1393  +    }
  1384   1394   
  1385   1395       /* Create a key for accessing the index entry */
  1386   1396       regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  1387   1397       for(i=0; i<pIdx->nColumn; i++){
  1388   1398         int idx = pIdx->aiColumn[i];
  1389   1399         if( idx==pTab->iPKey ){
  1390   1400           sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
................................................................................
  1397   1407       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  1398   1408       sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  1399   1409   
  1400   1410       /* Find out what action to take in case there is an indexing conflict */
  1401   1411       onError = pIdx->onError;
  1402   1412       if( onError==OE_None ){ 
  1403   1413         sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
         1414  +      sqlite3VdbeResolveLabel(v, addrSkipRow);
  1404   1415         continue;  /* pIdx is not a UNIQUE index */
  1405   1416       }
  1406   1417       if( overrideError!=OE_Default ){
  1407   1418         onError = overrideError;
  1408   1419       }else if( onError==OE_Default ){
  1409   1420         onError = OE_Abort;
  1410   1421       }
................................................................................
  1466   1477               pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  1467   1478           );
  1468   1479           seenReplace = 1;
  1469   1480           break;
  1470   1481         }
  1471   1482       }
  1472   1483       sqlite3VdbeJumpHere(v, j3);
         1484  +    sqlite3VdbeResolveLabel(v, addrSkipRow);
  1473   1485       sqlite3ReleaseTempReg(pParse, regR);
  1474   1486     }
  1475   1487     
  1476   1488     if( pbMayReplace ){
  1477   1489       *pbMayReplace = seenReplace;
  1478   1490     }
  1479   1491   }
................................................................................
  1495   1507     int *aRegIdx,       /* Register used by each index.  0 for unused indices */
  1496   1508     int isUpdate,       /* True for UPDATE, False for INSERT */
  1497   1509     int appendBias,     /* True if this is likely to be an append */
  1498   1510     int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  1499   1511   ){
  1500   1512     int i;
  1501   1513     Vdbe *v;
  1502         -  int nIdx;
  1503   1514     Index *pIdx;
  1504   1515     u8 pik_flags;
  1505   1516     int regData;
  1506   1517     int regRec;
  1507   1518   
  1508   1519     v = sqlite3GetVdbe(pParse);
  1509   1520     assert( v!=0 );
  1510   1521     assert( pTab->pSelect==0 );  /* This table is not a VIEW */
  1511         -  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  1512         -  for(i=nIdx-1; i>=0; i--){
         1522  +  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  1513   1523       if( aRegIdx[i]==0 ) continue;
         1524  +    if( pIdx->pPartIdxWhere ){
         1525  +      sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
         1526  +    }
  1514   1527       sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  1515   1528       if( useSeekResult ){
  1516   1529         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  1517   1530       }
  1518   1531     }
  1519   1532     regData = regRowid + 1;
  1520   1533     regRec = sqlite3GetTempReg(pParse);
................................................................................
  1608   1621   ** for index pDest in an insert transfer optimization.  The rules
  1609   1622   ** for a compatible index:
  1610   1623   **
  1611   1624   **    *   The index is over the same set of columns
  1612   1625   **    *   The same DESC and ASC markings occurs on all columns
  1613   1626   **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
  1614   1627   **    *   The same collating sequence on each column
         1628  +**    *   The index has the exact same WHERE clause
  1615   1629   */
  1616   1630   static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  1617   1631     int i;
  1618   1632     assert( pDest && pSrc );
  1619   1633     assert( pDest->pTable!=pSrc->pTable );
  1620   1634     if( pDest->nColumn!=pSrc->nColumn ){
  1621   1635       return 0;   /* Different number of columns */
................................................................................
  1629   1643       }
  1630   1644       if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  1631   1645         return 0;   /* Different sort orders */
  1632   1646       }
  1633   1647       if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  1634   1648         return 0;   /* Different collating sequences */
  1635   1649       }
         1650  +  }
         1651  +  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
         1652  +    return 0;     /* Different WHERE clauses */
  1636   1653     }
  1637   1654   
  1638   1655     /* If no test above fails then the indices must be compatible */
  1639   1656     return 1;
  1640   1657   }
  1641   1658   
  1642   1659   /*
................................................................................
  1785   1802         if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  1786   1803       }
  1787   1804       if( pSrcIdx==0 ){
  1788   1805         return 0;    /* pDestIdx has no corresponding index in pSrc */
  1789   1806       }
  1790   1807     }
  1791   1808   #ifndef SQLITE_OMIT_CHECK
  1792         -  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
         1809  +  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  1793   1810       return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
  1794   1811     }
  1795   1812   #endif
  1796   1813   #ifndef SQLITE_OMIT_FOREIGN_KEY
  1797   1814     /* Disallow the transfer optimization if the destination table constains
  1798   1815     ** any foreign key constraints.  This is more restrictive than necessary.
  1799   1816     ** But the main beneficiary of the transfer optimization is the VACUUM 

Changes to src/main.c.

  1096   1096         case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
  1097   1097         case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
  1098   1098         case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
  1099   1099         case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
  1100   1100         case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
  1101   1101         case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  1102   1102         case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
         1103  +      case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  1103   1104         case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
  1104   1105         case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
  1105   1106         case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
  1106   1107         case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
  1107   1108         case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
  1108   1109         case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  1109   1110         case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
................................................................................
  2461   2462     assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  2462   2463     memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  2463   2464     db->autoCommit = 1;
  2464   2465     db->nextAutovac = -1;
  2465   2466     db->szMmap = sqlite3GlobalConfig.szMmap;
  2466   2467     db->nextPagesize = 0;
  2467   2468     db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger
  2468         -#if !defined(SQLITE_DEAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
         2469  +#if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  2469   2470                    | SQLITE_AutoIndex
  2470   2471   #endif
  2471   2472   #if SQLITE_DEFAULT_FILE_FORMAT<4
  2472   2473                    | SQLITE_LegacyFileFmt
  2473   2474   #endif
  2474   2475   #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  2475   2476                    | SQLITE_LoadExtension

Changes to src/os_win.c.

    13     13   ** This file contains code that is specific to Windows.
    14     14   */
    15     15   #include "sqliteInt.h"
    16     16   #if SQLITE_OS_WIN               /* This file is used for Windows only */
    17     17   
    18     18   #ifdef __CYGWIN__
    19     19   # include <sys/cygwin.h>
           20  +# include <errno.h>
    20     21   #endif
    21     22   
    22     23   /*
    23     24   ** Include code that is common to all os_*.c files
    24     25   */
    25     26   #include "os_common.h"
    26     27   
................................................................................
   225    226   /*
   226    227    * The extra flags to use in calls to the Win32 heap APIs.  This value may be
   227    228    * zero for the default behavior.
   228    229    */
   229    230   #ifndef SQLITE_WIN32_HEAP_FLAGS
   230    231   #  define SQLITE_WIN32_HEAP_FLAGS     (0)
   231    232   #endif
          233  +
   232    234   
   233    235   /*
   234    236   ** The winMemData structure stores information required by the Win32-specific
   235    237   ** sqlite3_mem_methods implementation.
   236    238   */
   237    239   typedef struct winMemData winMemData;
   238    240   struct winMemData {
................................................................................
  3690   3692                          "winMapfile", pFd->zPath);
  3691   3693         /* Log the error, but continue normal operation using xRead/xWrite */
  3692   3694         OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
  3693   3695                  osGetCurrentProcessId(), pFd));
  3694   3696         return SQLITE_OK;
  3695   3697       }
  3696   3698       assert( (nMap % winSysInfo.dwPageSize)==0 );
         3699  +    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  3697   3700   #if SQLITE_OS_WINRT
  3698         -    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, nMap);
         3701  +    pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  3699   3702   #else
  3700         -    assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  3701   3703       pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  3702   3704   #endif
  3703   3705       if( pNew==NULL ){
  3704   3706         osCloseHandle(pFd->hMap);
  3705   3707         pFd->hMap = NULL;
  3706   3708         pFd->lastErrno = osGetLastError();
  3707   3709         winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
................................................................................
  3862   3864       zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  3863   3865     }
  3864   3866   #endif
  3865   3867     /* caller will handle out of memory */
  3866   3868     return zConverted;
  3867   3869   }
  3868   3870   
         3871  +/*
         3872  +** Maximum pathname length (in bytes) for windows.  The MAX_PATH macro is
         3873  +** in characters, so we allocate 3 bytes per character assuming worst-case
         3874  +** 3-bytes-per-character UTF8.
         3875  +*/
         3876  +#ifndef SQLITE_WIN32_MAX_PATH
         3877  +#  define SQLITE_WIN32_MAX_PATH   (MAX_PATH*3)
         3878  +#endif
         3879  +
  3869   3880   /*
  3870   3881   ** Create a temporary file name in zBuf.  zBuf must be big enough to
  3871   3882   ** hold at pVfs->mxPathname characters.
  3872   3883   */
  3873   3884   static int getTempname(int nBuf, char *zBuf){
  3874   3885     static char zChars[] =
  3875   3886       "abcdefghijklmnopqrstuvwxyz"
  3876   3887       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3877   3888       "0123456789";
  3878   3889     size_t i, j;
  3879   3890     int nTempPath;
  3880         -  char zTempPath[MAX_PATH+2];
         3891  +  char zTempPath[SQLITE_WIN32_MAX_PATH+2];
  3881   3892   
  3882   3893     /* It's odd to simulate an io-error here, but really this is just
  3883   3894     ** using the io-error infrastructure to test that SQLite handles this
  3884   3895     ** function failing. 
  3885   3896     */
  3886   3897     SimulateIOError( return SQLITE_IOERR );
  3887   3898   
  3888         -  memset(zTempPath, 0, MAX_PATH+2);
  3889         -
  3890   3899     if( sqlite3_temp_directory ){
  3891         -    sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
         3900  +    sqlite3_snprintf(SQLITE_WIN32_MAX_PATH-30, zTempPath, "%s",
         3901  +                     sqlite3_temp_directory);
  3892   3902     }
  3893   3903   #if !SQLITE_OS_WINRT
  3894   3904     else if( isNT() ){
  3895   3905       char *zMulti;
  3896   3906       WCHAR zWidePath[MAX_PATH];
  3897         -    osGetTempPathW(MAX_PATH-30, zWidePath);
         3907  +    if( osGetTempPathW(MAX_PATH-30, zWidePath)==0 ){
         3908  +      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
         3909  +      return SQLITE_IOERR_GETTEMPPATH;
         3910  +    }
  3898   3911       zMulti = unicodeToUtf8(zWidePath);
  3899   3912       if( zMulti ){
  3900         -      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
         3913  +      sqlite3_snprintf(SQLITE_WIN32_MAX_PATH-30, zTempPath, "%s", zMulti);
  3901   3914         sqlite3_free(zMulti);
  3902   3915       }else{
  3903   3916         OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3904   3917         return SQLITE_IOERR_NOMEM;
  3905   3918       }
  3906   3919     }
  3907   3920   #ifdef SQLITE_WIN32_HAS_ANSI
  3908   3921     else{
  3909   3922       char *zUtf8;
  3910         -    char zMbcsPath[MAX_PATH];
  3911         -    osGetTempPathA(MAX_PATH-30, zMbcsPath);
         3923  +    char zMbcsPath[SQLITE_WIN32_MAX_PATH];
         3924  +    if( osGetTempPathA(SQLITE_WIN32_MAX_PATH-30, zMbcsPath)==0 ){
         3925  +      OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
         3926  +      return SQLITE_IOERR_GETTEMPPATH;
         3927  +    }
  3912   3928       zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  3913   3929       if( zUtf8 ){
  3914         -      sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
         3930  +      sqlite3_snprintf(SQLITE_WIN32_MAX_PATH-30, zTempPath, "%s", zUtf8);
  3915   3931         sqlite3_free(zUtf8);
  3916   3932       }else{
  3917   3933         OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  3918   3934         return SQLITE_IOERR_NOMEM;
  3919   3935       }
  3920   3936     }
  3921         -#endif
  3922         -#endif
         3937  +#else
         3938  +  else{
         3939  +    /*
         3940  +    ** Compiled without ANSI support and the current operating system
         3941  +    ** is not Windows NT; therefore, just zero the temporary buffer.
         3942  +    */
         3943  +    memset(zTempPath, 0, SQLITE_WIN32_MAX_PATH+2);
         3944  +  }
         3945  +#endif /* SQLITE_WIN32_HAS_ANSI */
         3946  +#else
         3947  +  else{
         3948  +    /*
         3949  +    ** Compiled for WinRT and the sqlite3_temp_directory is not set;
         3950  +    ** therefore, just zero the temporary buffer.
         3951  +    */
         3952  +    memset(zTempPath, 0, SQLITE_WIN32_MAX_PATH+2);
         3953  +  }
         3954  +#endif /* !SQLITE_OS_WINRT */
  3923   3955   
  3924   3956     /* Check that the output buffer is large enough for the temporary file 
  3925   3957     ** name. If it is not, return SQLITE_ERROR.
  3926   3958     */
  3927   3959     nTempPath = sqlite3Strlen30(zTempPath);
  3928   3960   
  3929   3961     if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
................................................................................
  4001   4033     void *zConverted;              /* Filename in OS encoding */
  4002   4034     const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  4003   4035     int cnt = 0;
  4004   4036   
  4005   4037     /* If argument zPath is a NULL pointer, this function is required to open
  4006   4038     ** a temporary file. Use this buffer to store the file name in.
  4007   4039     */
  4008         -  char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
         4040  +  char zTmpname[SQLITE_WIN32_MAX_PATH+2];     /* Buffer used to create temp filename */
  4009   4041   
  4010   4042     int rc = SQLITE_OK;            /* Function Return Code */
  4011   4043   #if !defined(NDEBUG) || SQLITE_OS_WINCE
  4012   4044     int eType = flags&0xFFFFFF00;  /* Type of file to open */
  4013   4045   #endif
  4014   4046   
  4015   4047     int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
................................................................................
  4067   4099   #endif
  4068   4100   
  4069   4101     /* If the second argument to this function is NULL, generate a 
  4070   4102     ** temporary file name to use 
  4071   4103     */
  4072   4104     if( !zUtf8Name ){
  4073   4105       assert(isDelete && !isOpenJournal);
  4074         -    memset(zTmpname, 0, MAX_PATH+2);
  4075         -    rc = getTempname(MAX_PATH+2, zTmpname);
         4106  +    rc = getTempname(SQLITE_WIN32_MAX_PATH+2, zTmpname);
  4076   4107       if( rc!=SQLITE_OK ){
  4077   4108         OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  4078   4109         return rc;
  4079   4110       }
  4080   4111       zUtf8Name = zTmpname;
  4081   4112     }
  4082   4113   
................................................................................
  4499   4530     int nFull,                    /* Size of output buffer in bytes */
  4500   4531     char *zFull                   /* Output buffer */
  4501   4532   ){
  4502   4533     
  4503   4534   #if defined(__CYGWIN__)
  4504   4535     SimulateIOError( return SQLITE_ERROR );
  4505   4536     UNUSED_PARAMETER(nFull);
  4506         -  assert( pVfs->mxPathname>=MAX_PATH );
         4537  +  assert( pVfs->mxPathname>=SQLITE_WIN32_MAX_PATH );
  4507   4538     assert( nFull>=pVfs->mxPathname );
  4508   4539     if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  4509   4540       /*
  4510   4541       ** NOTE: We are dealing with a relative path name and the data
  4511   4542       **       directory has been set.  Therefore, use it as the basis
  4512   4543       **       for converting the relative path name to an absolute
  4513   4544       **       one by prepending the data directory and a slash.
  4514   4545       */
  4515         -    char zOut[MAX_PATH+1];
  4516         -    memset(zOut, 0, MAX_PATH+1);
  4517         -    cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
  4518         -                     MAX_PATH+1);
         4546  +    char zOut[SQLITE_WIN32_MAX_PATH+1];
         4547  +    if( cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
         4548  +                         SQLITE_WIN32_MAX_PATH+1)<0 ){
         4549  +      winLogError(SQLITE_CANTOPEN_FULLPATH, (DWORD)errno, "cygwin_conv_path",
         4550  +                  zRelative);
         4551  +      return SQLITE_CANTOPEN_FULLPATH;
         4552  +    }
  4519   4553       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
  4520   4554                        sqlite3_data_directory, zOut);
  4521   4555     }else{
  4522         -    cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull);
         4556  +    if( cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull)<0 ){
         4557  +      winLogError(SQLITE_CANTOPEN_FULLPATH, (DWORD)errno, "cygwin_conv_path",
         4558  +                  zRelative);
         4559  +      return SQLITE_CANTOPEN_FULLPATH;
         4560  +    }
  4523   4561     }
  4524   4562     return SQLITE_OK;
  4525   4563   #endif
  4526   4564   
  4527   4565   #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  4528   4566     SimulateIOError( return SQLITE_ERROR );
  4529   4567     /* WinCE has no concept of a relative pathname, or so I am told. */
................................................................................
  4857   4895   /*
  4858   4896   ** Initialize and deinitialize the operating system interface.
  4859   4897   */
  4860   4898   int sqlite3_os_init(void){
  4861   4899     static sqlite3_vfs winVfs = {
  4862   4900       3,                   /* iVersion */
  4863   4901       sizeof(winFile),     /* szOsFile */
  4864         -    MAX_PATH,            /* mxPathname */
         4902  +    SQLITE_WIN32_MAX_PATH, /* mxPathname */
  4865   4903       0,                   /* pNext */
  4866   4904       "win32",             /* zName */
  4867   4905       0,                   /* pAppData */
  4868   4906       winOpen,             /* xOpen */
  4869   4907       winDelete,           /* xDelete */
  4870   4908       winAccess,           /* xAccess */
  4871   4909       winFullPathname,     /* xFullPathname */

Changes to src/parse.y.

   413    413   
   414    414   select(A) ::= oneselect(X).                      {A = X;}
   415    415   %ifndef SQLITE_OMIT_COMPOUND_SELECT
   416    416   select(A) ::= select(X) multiselect_op(Y) oneselect(Z).  {
   417    417     if( Z ){
   418    418       Z->op = (u8)Y;
   419    419       Z->pPrior = X;
          420  +    if( Y!=TK_ALL ) pParse->hasCompound = 1;
   420    421     }else{
   421    422       sqlite3SelectDelete(pParse->db, X);
   422    423     }
   423    424     A = Z;
   424    425   }
   425    426   %type multiselect_op {int}
   426    427   multiselect_op(A) ::= UNION(OP).             {A = @OP;}
................................................................................
  1121   1122   nexprlist(A) ::= expr(Y).
  1122   1123       {A = sqlite3ExprListAppend(pParse,0,Y.pExpr);}
  1123   1124   
  1124   1125   
  1125   1126   ///////////////////////////// The CREATE INDEX command ///////////////////////
  1126   1127   //
  1127   1128   cmd ::= createkw(S) uniqueflag(U) INDEX ifnotexists(NE) nm(X) dbnm(D)
  1128         -        ON nm(Y) LP idxlist(Z) RP(E). {
         1129  +        ON nm(Y) LP idxlist(Z) RP where_opt(W). {
  1129   1130     sqlite3CreateIndex(pParse, &X, &D, 
  1130   1131                        sqlite3SrcListAppend(pParse->db,0,&Y,0), Z, U,
  1131         -                      &S, &E, SQLITE_SO_ASC, NE);
         1132  +                      &S, W, SQLITE_SO_ASC, NE);
  1132   1133   }
  1133   1134   
  1134   1135   %type uniqueflag {int}
  1135   1136   uniqueflag(A) ::= UNIQUE.  {A = OE_Abort;}
  1136   1137   uniqueflag(A) ::= .        {A = OE_None;}
  1137   1138   
  1138   1139   %type idxlist {ExprList*}

Changes to src/pragma.c.

  1396   1396           for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  1397   1397             sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  1398   1398             cnt++;
  1399   1399           }
  1400   1400         }
  1401   1401   
  1402   1402         /* Make sure sufficient number of registers have been allocated */
  1403         -      if( pParse->nMem < cnt+4 ){
  1404         -        pParse->nMem = cnt+4;
  1405         -      }
         1403  +      pParse->nMem = MAX( pParse->nMem, cnt+7 );
  1406   1404   
  1407   1405         /* Do the b-tree integrity checks */
  1408   1406         sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  1409   1407         sqlite3VdbeChangeP5(v, (u8)i);
  1410   1408         addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  1411   1409         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  1412   1410            sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
................................................................................
  1423   1421           Index *pIdx;
  1424   1422           int loopTop;
  1425   1423   
  1426   1424           if( pTab->pIndex==0 ) continue;
  1427   1425           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
  1428   1426           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  1429   1427           sqlite3VdbeJumpHere(v, addr);
         1428  +        sqlite3ExprCacheClear(pParse);
  1430   1429           sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  1431         -        sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
  1432         -        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
  1433         -        sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
         1430  +        for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
         1431  +          sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */
         1432  +        }
         1433  +        pParse->nMem = MAX(pParse->nMem, 7+j);
         1434  +        loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1;
  1434   1435           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  1435         -          int jmp2;
         1436  +          int jmp2, jmp3;
  1436   1437             int r1;
  1437   1438             static const VdbeOpList idxErr[] = {
  1438   1439               { OP_AddImm,      1, -1,  0},
  1439   1440               { OP_String8,     0,  3,  0},    /* 1 */
  1440   1441               { OP_Rowid,       1,  4,  0},
  1441   1442               { OP_String8,     0,  5,  0},    /* 3 */
  1442   1443               { OP_String8,     0,  6,  0},    /* 4 */
................................................................................
  1443   1444               { OP_Concat,      4,  3,  3},
  1444   1445               { OP_Concat,      5,  3,  3},
  1445   1446               { OP_Concat,      6,  3,  3},
  1446   1447               { OP_ResultRow,   3,  1,  0},
  1447   1448               { OP_IfPos,       1,  0,  0},    /* 9 */
  1448   1449               { OP_Halt,        0,  0,  0},
  1449   1450             };
  1450         -          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
         1451  +          r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3);
         1452  +          sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1);  /* increment entry count */
  1451   1453             jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  1452   1454             addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  1453   1455             sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  1454   1456             sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  1455   1457             sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  1456   1458             sqlite3VdbeJumpHere(v, addr+9);
  1457   1459             sqlite3VdbeJumpHere(v, jmp2);
         1460  +          sqlite3VdbeResolveLabel(v, jmp3);
  1458   1461           }
  1459         -        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
  1460         -        sqlite3VdbeJumpHere(v, loopTop);
         1462  +        sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop);
         1463  +        sqlite3VdbeJumpHere(v, loopTop-1);
         1464  +#ifndef SQLITE_OMIT_BTREECOUNT
         1465  +        sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, 
         1466  +                     "wrong # of entries in index ", P4_STATIC);
  1461   1467           for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  1462         -          static const VdbeOpList cntIdx[] = {
  1463         -             { OP_Integer,      0,  3,  0},
  1464         -             { OP_Rewind,       0,  0,  0},  /* 1 */
  1465         -             { OP_AddImm,       3,  1,  0},
  1466         -             { OP_Next,         0,  0,  0},  /* 3 */
  1467         -             { OP_Eq,           2,  0,  3},  /* 4 */
  1468         -             { OP_AddImm,       1, -1,  0},
  1469         -             { OP_String8,      0,  2,  0},  /* 6 */
  1470         -             { OP_String8,      0,  3,  0},  /* 7 */
  1471         -             { OP_Concat,       3,  2,  2},
  1472         -             { OP_ResultRow,    2,  1,  0},
  1473         -          };
  1474         -          addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
         1468  +          addr = sqlite3VdbeCurrentAddr(v);
         1469  +          sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
  1475   1470             sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  1476         -          sqlite3VdbeJumpHere(v, addr);
  1477         -          addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
  1478         -          sqlite3VdbeChangeP1(v, addr+1, j+2);
  1479         -          sqlite3VdbeChangeP2(v, addr+1, addr+4);
  1480         -          sqlite3VdbeChangeP1(v, addr+3, j+2);
  1481         -          sqlite3VdbeChangeP2(v, addr+3, addr+2);
  1482         -          sqlite3VdbeJumpHere(v, addr+4);
  1483         -          sqlite3VdbeChangeP4(v, addr+6, 
  1484         -                     "wrong # of entries in index ", P4_STATIC);
  1485         -          sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
         1471  +          sqlite3VdbeAddOp2(v, OP_Count, j+2, 3);
         1472  +          sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3);
         1473  +          sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
         1474  +          sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
         1475  +          sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
         1476  +          sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  1486   1477           }
         1478  +#endif /* SQLITE_OMIT_BTREECOUNT */
  1487   1479         } 
  1488   1480       }
  1489   1481       addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  1490   1482       sqlite3VdbeChangeP2(v, addr, -mxErr);
  1491   1483       sqlite3VdbeJumpHere(v, addr+1);
  1492   1484       sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  1493   1485     }else

Changes to src/resolve.c.

   236    236     ExprSetIrreducible(pExpr);
   237    237   
   238    238     /* Translate the schema name in zDb into a pointer to the corresponding
   239    239     ** schema.  If not found, pSchema will remain NULL and nothing will match
   240    240     ** resulting in an appropriate error message toward the end of this routine
   241    241     */
   242    242     if( zDb ){
   243         -    for(i=0; i<db->nDb; i++){
   244         -      assert( db->aDb[i].zName );
   245         -      if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
   246         -        pSchema = db->aDb[i].pSchema;
   247         -        break;
          243  +    testcase( pNC->ncFlags & NC_PartIdx );
          244  +    testcase( pNC->ncFlags & NC_IsCheck );
          245  +    if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
          246  +      /* Silently ignore database qualifiers inside CHECK constraints and partial
          247  +      ** indices.  Do not raise errors because that might break legacy and
          248  +      ** because it does not hurt anything to just ignore the database name. */
          249  +      zDb = 0;
          250  +    }else{
          251  +      for(i=0; i<db->nDb; i++){
          252  +        assert( db->aDb[i].zName );
          253  +        if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
          254  +          pSchema = db->aDb[i].pSchema;
          255  +          break;
          256  +        }
   248    257         }
   249    258       }
   250    259     }
   251    260   
   252    261     /* Start at the inner-most context and move outward until a match is found */
   253    262     while( pNC && cnt==0 ){
   254    263       ExprList *pEList;
................................................................................
   517    526         testcase( iCol==BMS-1 );
   518    527         pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
   519    528       }
   520    529       ExprSetProperty(p, EP_Resolved);
   521    530     }
   522    531     return p;
   523    532   }
          533  +
          534  +/*
          535  +** Report an error that an expression is not valid for a partial index WHERE
          536  +** clause.
          537  +*/
          538  +static void notValidPartIdxWhere(
          539  +  Parse *pParse,       /* Leave error message here */
          540  +  NameContext *pNC,    /* The name context */
          541  +  const char *zMsg     /* Type of error */
          542  +){
          543  +  if( (pNC->ncFlags & NC_PartIdx)!=0 ){
          544  +    sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
          545  +                    zMsg);
          546  +  }
          547  +}
          548  +
          549  +#ifndef SQLITE_OMIT_CHECK
          550  +/*
          551  +** Report an error that an expression is not valid for a CHECK constraint.
          552  +*/
          553  +static void notValidCheckConstraint(
          554  +  Parse *pParse,       /* Leave error message here */
          555  +  NameContext *pNC,    /* The name context */
          556  +  const char *zMsg     /* Type of error */
          557  +){
          558  +  if( (pNC->ncFlags & NC_IsCheck)!=0 ){
          559  +    sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
          560  +  }
          561  +}
          562  +#else
          563  +# define notValidCheckConstraint(P,N,M)
          564  +#endif
          565  +
   524    566   
   525    567   /*
   526    568   ** This routine is callback for sqlite3WalkExpr().
   527    569   **
   528    570   ** Resolve symbolic names into TK_COLUMN operators for the current
   529    571   ** node in the expression tree.  Return 0 to continue the search down
   530    572   ** the tree or 2 to abort the tree walk.
................................................................................
   617    659         int nId;                    /* Number of characters in function name */
   618    660         const char *zId;            /* The function name. */
   619    661         FuncDef *pDef;              /* Information about the function */
   620    662         u8 enc = ENC(pParse->db);   /* The database encoding */
   621    663   
   622    664         testcase( pExpr->op==TK_CONST_FUNC );
   623    665         assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
          666  +      notValidPartIdxWhere(pParse, pNC, "functions");
   624    667         zId = pExpr->u.zToken;
   625    668         nId = sqlite3Strlen30(zId);
   626    669         pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
   627    670         if( pDef==0 ){
   628    671           pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
   629    672           if( pDef==0 ){
   630    673             no_such_func = 1;
................................................................................
   682    725       case TK_SELECT:
   683    726       case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
   684    727   #endif
   685    728       case TK_IN: {
   686    729         testcase( pExpr->op==TK_IN );
   687    730         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
   688    731           int nRef = pNC->nRef;
   689         -#ifndef SQLITE_OMIT_CHECK
   690         -        if( (pNC->ncFlags & NC_IsCheck)!=0 ){
   691         -          sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
   692         -        }
   693         -#endif
          732  +        notValidCheckConstraint(pParse, pNC, "subqueries");
          733  +        notValidPartIdxWhere(pParse, pNC, "subqueries");
   694    734           sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
   695    735           assert( pNC->nRef>=nRef );
   696    736           if( nRef!=pNC->nRef ){
   697    737             ExprSetProperty(pExpr, EP_VarSelect);
   698    738           }
   699    739         }
   700    740         break;
   701    741       }
   702         -#ifndef SQLITE_OMIT_CHECK
   703    742       case TK_VARIABLE: {
   704         -      if( (pNC->ncFlags & NC_IsCheck)!=0 ){
   705         -        sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
   706         -      }
          743  +      notValidCheckConstraint(pParse, pNC, "parameters");
          744  +      notValidPartIdxWhere(pParse, pNC, "parameters");
   707    745         break;
   708    746       }
   709         -#endif
   710    747     }
   711    748     return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
   712    749   }
   713    750   
   714    751   /*
   715    752   ** pEList is a list of expressions which are really the result set of the
   716    753   ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
................................................................................
   793    830     if( rc ) return 0;
   794    831   
   795    832     /* Try to match the ORDER BY expression against an expression
   796    833     ** in the result set.  Return an 1-based index of the matching
   797    834     ** result-set entry.
   798    835     */
   799    836     for(i=0; i<pEList->nExpr; i++){
   800         -    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
          837  +    if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
   801    838         return i+1;
   802    839       }
   803    840     }
   804    841   
   805    842     /* If no match, return 0. */
   806    843     return 0;
   807    844   }
................................................................................
  1021   1058   
  1022   1059       /* Otherwise, treat the ORDER BY term as an ordinary expression */
  1023   1060       pItem->iOrderByCol = 0;
  1024   1061       if( sqlite3ResolveExprNames(pNC, pE) ){
  1025   1062         return 1;
  1026   1063       }
  1027   1064       for(j=0; j<pSelect->pEList->nExpr; j++){
  1028         -      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
         1065  +      if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  1029   1066           pItem->iOrderByCol = j+1;
  1030   1067         }
  1031   1068       }
  1032   1069     }
  1033   1070     return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  1034   1071   }
  1035   1072   
................................................................................
  1327   1364     memset(&w, 0, sizeof(w));
  1328   1365     w.xExprCallback = resolveExprStep;
  1329   1366     w.xSelectCallback = resolveSelectStep;
  1330   1367     w.pParse = pParse;
  1331   1368     w.u.pNC = pOuterNC;
  1332   1369     sqlite3WalkSelect(&w, p);
  1333   1370   }
         1371  +
         1372  +/*
         1373  +** Resolve names in expressions that can only reference a single table:
         1374  +**
         1375  +**    *   CHECK constraints
         1376  +**    *   WHERE clauses on partial indices
         1377  +**
         1378  +** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
         1379  +** is set to -1 and the Expr.iColumn value is set to the column number.
         1380  +**
         1381  +** Any errors cause an error message to be set in pParse.
         1382  +*/
         1383  +void sqlite3ResolveSelfReference(
         1384  +  Parse *pParse,      /* Parsing context */
         1385  +  Table *pTab,        /* The table being referenced */
         1386  +  int type,           /* NC_IsCheck or NC_PartIdx */
         1387  +  Expr *pExpr,        /* Expression to resolve.  May be NULL. */
         1388  +  ExprList *pList     /* Expression list to resolve.  May be NUL. */
         1389  +){
         1390  +  SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
         1391  +  NameContext sNC;                /* Name context for pParse->pNewTable */
         1392  +  int i;                          /* Loop counter */
         1393  +
         1394  +  assert( type==NC_IsCheck || type==NC_PartIdx );
         1395  +  memset(&sNC, 0, sizeof(sNC));
         1396  +  memset(&sSrc, 0, sizeof(sSrc));
         1397  +  sSrc.nSrc = 1;
         1398  +  sSrc.a[0].zName = pTab->zName;
         1399  +  sSrc.a[0].pTab = pTab;
         1400  +  sSrc.a[0].iCursor = -1;
         1401  +  sNC.pParse = pParse;
         1402  +  sNC.pSrcList = &sSrc;
         1403  +  sNC.ncFlags = type;
         1404  +  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
         1405  +  if( pList ){
         1406  +    for(i=0; i<pList->nExpr; i++){
         1407  +      if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
         1408  +        return;
         1409  +      }
         1410  +    }
         1411  +  }
         1412  +}

Changes to src/select.c.

   797    797     ** there is a sorter, in which case the sorter has already limited
   798    798     ** the output for us.
   799    799     */
   800    800     if( pOrderBy==0 && p->iLimit ){
   801    801       sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
   802    802     }
   803    803   }
          804  +
          805  +/*
          806  +** Allocate a KeyInfo object sufficient for an index of N columns.
          807  +**
          808  +** Actually, always allocate one extra column for the rowid at the end
          809  +** of the index.  So the KeyInfo returned will have space sufficient for
          810  +** N+1 columns.
          811  +*/
          812  +KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){
          813  +  KeyInfo *p = sqlite3DbMallocZero(db, 
          814  +                   sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1));
          815  +  if( p ){
          816  +    p->aSortOrder = (u8*)&p->aColl[N+1];
          817  +    p->nField = (u16)N;
          818  +    p->enc = ENC(db);
          819  +    p->db = db;
          820  +  }
          821  +  return p;
          822  +}
   804    823   
   805    824   /*
   806    825   ** Given an expression list, generate a KeyInfo structure that records
   807    826   ** the collating sequence for each expression in that expression list.
   808    827   **
   809    828   ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
   810    829   ** KeyInfo structure is appropriate for initializing a virtual index to
................................................................................
   814    833   **
   815    834   ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
   816    835   ** function is responsible for seeing that this structure is eventually
   817    836   ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
   818    837   ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
   819    838   */
   820    839   static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
   821         -  sqlite3 *db = pParse->db;
   822    840     int nExpr;
   823    841     KeyInfo *pInfo;
   824    842     struct ExprList_item *pItem;
          843  +  sqlite3 *db = pParse->db;
   825    844     int i;
   826    845   
   827    846     nExpr = pList->nExpr;
   828         -  pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
          847  +  pInfo = sqlite3KeyInfoAlloc(db, nExpr);
   829    848     if( pInfo ){
   830         -    pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
   831         -    pInfo->nField = (u16)nExpr;
   832         -    pInfo->enc = ENC(db);
   833         -    pInfo->db = db;
   834    849       for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
   835    850         CollSeq *pColl;
   836    851         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
   837         -      if( !pColl ){
   838         -        pColl = db->pDfltColl;
   839         -      }
          852  +      if( !pColl ) pColl = db->pDfltColl;
   840    853         pInfo->aColl[i] = pColl;
   841    854         pInfo->aSortOrder[i] = pItem->sortOrder;
   842    855       }
   843    856     }
   844    857     return pInfo;
   845    858   }
   846    859   
................................................................................
  1938   1951       KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
  1939   1952       Select *pLoop;                /* For looping through SELECT statements */
  1940   1953       CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
  1941   1954       int nCol;                     /* Number of columns in result set */
  1942   1955   
  1943   1956       assert( p->pRightmost==p );
  1944   1957       nCol = p->pEList->nExpr;
  1945         -    pKeyInfo = sqlite3DbMallocZero(db,
  1946         -                       sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
         1958  +    pKeyInfo = sqlite3KeyInfoAlloc(db, nCol);
  1947   1959       if( !pKeyInfo ){
  1948   1960         rc = SQLITE_NOMEM;
  1949   1961         goto multi_select_end;
  1950   1962       }
  1951         -
  1952         -    pKeyInfo->enc = ENC(db);
  1953         -    pKeyInfo->nField = (u16)nCol;
  1954         -
  1955   1963       for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  1956   1964         *apColl = multiSelectCollSeq(pParse, p, i);
  1957   1965         if( 0==*apColl ){
  1958   1966           *apColl = db->pDfltColl;
  1959   1967         }
  1960   1968       }
  1961         -    pKeyInfo->aSortOrder = (u8*)apColl;
  1962   1969   
  1963   1970       for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  1964   1971         for(i=0; i<2; i++){
  1965   1972           int addr = pLoop->addrOpenEphm[i];
  1966   1973           if( addr<0 ){
  1967   1974             /* If [0] is unused then [1] is also unused.  So we can
  1968   1975             ** always safely abort as soon as the first unused slot is found */
................................................................................
  2323   2330     aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  2324   2331     if( aPermute ){
  2325   2332       struct ExprList_item *pItem;
  2326   2333       for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  2327   2334         assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
  2328   2335         aPermute[i] = pItem->iOrderByCol - 1;
  2329   2336       }
  2330         -    pKeyMerge =
  2331         -      sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
         2337  +    pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy);
  2332   2338       if( pKeyMerge ){
  2333         -      pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
  2334         -      pKeyMerge->nField = (u16)nOrderBy;
  2335         -      pKeyMerge->enc = ENC(db);
  2336   2339         for(i=0; i<nOrderBy; i++){
  2337   2340           CollSeq *pColl;
  2338   2341           Expr *pTerm = pOrderBy->a[i].pExpr;
  2339   2342           if( pTerm->flags & EP_Collate ){
  2340   2343             pColl = sqlite3ExprCollSeq(pParse, pTerm);
  2341   2344           }else{
  2342   2345             pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
................................................................................
  2365   2368       regPrev = 0;
  2366   2369     }else{
  2367   2370       int nExpr = p->pEList->nExpr;
  2368   2371       assert( nOrderBy>=nExpr || db->mallocFailed );
  2369   2372       regPrev = pParse->nMem+1;
  2370   2373       pParse->nMem += nExpr+1;
  2371   2374       sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  2372         -    pKeyDup = sqlite3DbMallocZero(db,
  2373         -                  sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
         2375  +    pKeyDup = sqlite3KeyInfoAlloc(db, nExpr);
  2374   2376       if( pKeyDup ){
  2375         -      pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
  2376         -      pKeyDup->nField = (u16)nExpr;
  2377         -      pKeyDup->enc = ENC(db);
  2378   2377         for(i=0; i<nExpr; i++){
  2379   2378           pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  2380   2379           pKeyDup->aSortOrder[i] = 0;
  2381   2380         }
  2382   2381       }
  2383   2382     }
  2384   2383    
................................................................................
  3636   3635   ** If anything goes wrong, an error message is written into pParse.
  3637   3636   ** The calling function can detect the problem by looking at pParse->nErr
  3638   3637   ** and/or pParse->db->mallocFailed.
  3639   3638   */
  3640   3639   static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  3641   3640     Walker w;
  3642   3641     memset(&w, 0, sizeof(w));
  3643         -  w.xSelectCallback = convertCompoundSelectToSubquery;
  3644   3642     w.xExprCallback = exprWalkNoop;
  3645   3643     w.pParse = pParse;
  3646         -  sqlite3WalkSelect(&w, pSelect);
         3644  +  if( pParse->hasCompound ){
         3645  +    w.xSelectCallback = convertCompoundSelectToSubquery;
         3646  +    sqlite3WalkSelect(&w, pSelect);
         3647  +  }
  3647   3648     w.xSelectCallback = selectExpander;
  3648   3649     sqlite3WalkSelect(&w, pSelect);
  3649   3650   }
  3650   3651   
  3651   3652   
  3652   3653   #ifndef SQLITE_OMIT_SUBQUERY
  3653   3654   /*
................................................................................
  4173   4174     /* If there is both a GROUP BY and an ORDER BY clause and they are
  4174   4175     ** identical, then disable the ORDER BY clause since the GROUP BY
  4175   4176     ** will cause elements to come out in the correct order.  This is
  4176   4177     ** an optimization - the correct answer should result regardless.
  4177   4178     ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  4178   4179     ** to disable this optimization for testing purposes.
  4179   4180     */
  4180         -  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
         4181  +  if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
  4181   4182            && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
  4182   4183       pOrderBy = 0;
  4183   4184     }
  4184   4185   
  4185   4186     /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
  4186   4187     ** if the select-list is the same as the ORDER BY list, then this query
  4187   4188     ** can be rewritten as a GROUP BY. In other words, this:
................................................................................
  4194   4195     **
  4195   4196     ** The second form is preferred as a single index (or temp-table) may be 
  4196   4197     ** used for both the ORDER BY and DISTINCT processing. As originally 
  4197   4198     ** written the query must use a temp-table for at least one of the ORDER 
  4198   4199     ** BY and DISTINCT, and an index or separate temp-table for the other.
  4199   4200     */
  4200   4201     if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
  4201         -   && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
         4202  +   && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
  4202   4203     ){
  4203   4204       p->selFlags &= ~SF_Distinct;
  4204   4205       p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  4205   4206       pGroupBy = p->pGroupBy;
  4206   4207       pOrderBy = 0;
  4207   4208       /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  4208   4209       ** the sDistinct.isTnct is still set.  Hence, isTnct represents the

Changes to src/shell.c.

    49     49   # include <editline/editline.h>
    50     50   #endif
    51     51   #if defined(HAVE_READLINE) && HAVE_READLINE==1
    52     52   # include <readline/readline.h>
    53     53   # include <readline/history.h>
    54     54   #endif
    55     55   #if !defined(HAVE_EDITLINE) && (!defined(HAVE_READLINE) || HAVE_READLINE!=1)
    56         -# define readline(p) local_getline(p,stdin,0)
    57     56   # define add_history(X)
    58     57   # define read_history(X)
    59     58   # define write_history(X)
    60     59   # define stifle_history(X)
    61     60   #endif
    62     61   
    63     62   #if defined(_WIN32) || defined(WIN32)
    64     63   # include <io.h>
    65     64   #define isatty(h) _isatty(h)
    66     65   #define access(f,m) _access((f),(m))
    67     66   #undef popen
    68         -#define popen(a,b) _popen((a),(b))
           67  +#define popen _popen
    69     68   #undef pclose
    70     69   #define pclose _pclose
    71     70   #else
    72     71   /* Make sure isatty() has a prototype.
    73     72   */
    74     73   extern int isatty(int);
    75     74   #endif
           75  +
           76  +/* popen and pclose are not C89 functions and so are sometimes omitted from
           77  +** the <stdio.h> header */
           78  +FILE *popen(const char*,const char*);
           79  +int pclose(FILE*);
    76     80   
    77     81   #if defined(_WIN32_WCE)
    78     82   /* Windows CE (arm-wince-mingw32ce-gcc) does not provide isatty()
    79     83    * thus we always assume that we have a console. That can be
    80     84    * overridden with the -batch command line option.
    81     85    */
    82     86   #define isatty(x) 1
................................................................................
   328    332   
   329    333   /*
   330    334   ** This routine reads a line of text from FILE in, stores
   331    335   ** the text in memory obtained from malloc() and returns a pointer
   332    336   ** to the text.  NULL is returned at end of file, or if malloc()
   333    337   ** fails.
   334    338   **
   335         -** The interface is like "readline" but no command-line editing
   336         -** is done.
          339  +** If zLine is not NULL then it is a malloced buffer returned from
          340  +** a previous call to this routine that may be reused.
   337    341   */
   338         -static char *local_getline(char *zPrompt, FILE *in, int csvFlag){
   339         -  char *zLine;
   340         -  int nLine;
   341         -  int n;
   342         -  int inQuote = 0;
          342  +static char *local_getline(char *zLine, FILE *in){
          343  +  int nLine = zLine==0 ? 0 : 100;
          344  +  int n = 0;
   343    345   
   344         -  if( zPrompt && *zPrompt ){
   345         -    printf("%s",zPrompt);
   346         -    fflush(stdout);
   347         -  }
   348         -  nLine = 100;
   349         -  zLine = malloc( nLine );
   350         -  if( zLine==0 ) return 0;
   351         -  n = 0;
   352    346     while( 1 ){
   353    347       if( n+100>nLine ){
   354    348         nLine = nLine*2 + 100;
   355    349         zLine = realloc(zLine, nLine);
   356    350         if( zLine==0 ) return 0;
   357    351       }
   358    352       if( fgets(&zLine[n], nLine - n, in)==0 ){
................................................................................
   359    353         if( n==0 ){
   360    354           free(zLine);
   361    355           return 0;
   362    356         }
   363    357         zLine[n] = 0;
   364    358         break;
   365    359       }
   366         -    while( zLine[n] ){
   367         -      if( zLine[n]=='"' ) inQuote = !inQuote;
   368         -      n++;
   369         -    }
   370         -    if( n>0 && zLine[n-1]=='\n' && (!inQuote || !csvFlag) ){
          360  +    while( zLine[n] ) n++;
          361  +    if( n>0 && zLine[n-1]=='\n' ){
   371    362         n--;
   372    363         if( n>0 && zLine[n-1]=='\r' ) n--;
   373    364         zLine[n] = 0;
   374    365         break;
   375    366       }
   376    367     }
   377         -  zLine = realloc( zLine, n+1 );
   378    368     return zLine;
   379    369   }
   380    370   
   381    371   /*
   382    372   ** Retrieve a single line of input text.
   383    373   **
   384         -** zPrior is a string of prior text retrieved.  If not the empty
   385         -** string, then issue a continuation prompt.
          374  +** If in==0 then read from standard input and prompt before each line.
          375  +** If isContinuation is true, then a continuation prompt is appropriate.
          376  +** If isContinuation is zero, then the main prompt should be used.
          377  +**
          378  +** If zPrior is not NULL then it is a buffer from a prior call to this
          379  +** routine that can be reused.
          380  +**
          381  +** The result is stored in space obtained from malloc() and must either
          382  +** be freed by the caller or else passed back into this routine via the
          383  +** zPrior argument for reuse.
   386    384   */
   387         -static char *one_input_line(const char *zPrior, FILE *in){
          385  +static char *one_input_line(FILE *in, char *zPrior, int isContinuation){
   388    386     char *zPrompt;
   389    387     char *zResult;
   390    388     if( in!=0 ){
   391         -    return local_getline(0, in, 0);
   392         -  }
   393         -  if( zPrior && zPrior[0] ){
   394         -    zPrompt = continuePrompt;
          389  +    zResult = local_getline(zPrior, in);
   395    390     }else{
   396         -    zPrompt = mainPrompt;
   397         -  }
   398         -  zResult = readline(zPrompt);
          391  +    zPrompt = isContinuation ? continuePrompt : mainPrompt;
   399    392   #if defined(HAVE_READLINE) && HAVE_READLINE==1
   400         -  if( zResult && *zResult ) add_history(zResult);
          393  +    free(zPrior);
          394  +    zResult = readline(zPrompt);
          395  +    if( zResult && *zResult ) add_history(zResult);
          396  +#else
          397  +    printf("%s", zPrompt);
          398  +    fflush(stdout);
          399  +    zResult = local_getline(zPrior, stdin);
   401    400   #endif
          401  +  }
   402    402     return zResult;
   403    403   }
   404    404   
   405    405   struct previous_mode_data {
   406    406     int valid;        /* Is there legit data in here? */
   407    407     int mode;
   408    408     int showHeader;
................................................................................
  1986   1986     if( c=='i' && strncmp(azArg[0], "import", n)==0 && nArg==3 ){
  1987   1987       char *zTable = azArg[2];    /* Insert data into this table */
  1988   1988       char *zFile = azArg[1];     /* Name of file to extra content from */
  1989   1989       sqlite3_stmt *pStmt = NULL; /* A statement */
  1990   1990       int nCol;                   /* Number of columns in the table */
  1991   1991       int nByte;                  /* Number of bytes in an SQL string */
  1992   1992       int i, j;                   /* Loop counters */
         1993  +    int needCommit;             /* True to COMMIT or ROLLBACK at end */
  1993   1994       int nSep;                   /* Number of bytes in p->separator[] */
  1994   1995       char *zSql;                 /* An SQL statement */
  1995   1996       CSVReader sCsv;             /* Reader context */
  1996   1997       int (*xCloser)(FILE*);      /* Procedure to close th3 connection */
  1997   1998   
  1998   1999       seenInterrupt = 0;
  1999   2000       memset(&sCsv, 0, sizeof(sCsv));
................................................................................
  2087   2088       sqlite3_free(zSql);
  2088   2089       if( rc ){
  2089   2090         fprintf(stderr, "Error: %s\n", sqlite3_errmsg(db));
  2090   2091         if (pStmt) sqlite3_finalize(pStmt);
  2091   2092         xCloser(sCsv.in);
  2092   2093         return 1;
  2093   2094       }
         2095  +    needCommit = sqlite3_get_autocommit(db);
         2096  +    if( needCommit ) sqlite3_exec(db, "BEGIN", 0, 0, 0);
  2094   2097       do{
  2095   2098         int startLine = sCsv.nLine;
  2096   2099         for(i=0; i<nCol; i++){
  2097   2100           char *z = csv_read_one_field(&sCsv);
  2098   2101           if( z==0 && i==0 ) break;
  2099   2102           sqlite3_bind_text(pStmt, i+1, z, -1, SQLITE_TRANSIENT);
  2100   2103           if( i<nCol-1 && sCsv.cTerm!=sCsv.cSeparator ){
................................................................................
  2123   2126           }
  2124   2127         }
  2125   2128       }while( sCsv.cTerm!=EOF );
  2126   2129   
  2127   2130       xCloser(sCsv.in);
  2128   2131       sqlite3_free(sCsv.z);
  2129   2132       sqlite3_finalize(pStmt);
  2130         -    sqlite3_exec(p->db, "COMMIT", 0, 0, 0);
         2133  +    if( needCommit ) sqlite3_exec(db, "COMMIT", 0, 0, 0);
  2131   2134     }else
  2132   2135   
  2133   2136     if( c=='i' && strncmp(azArg[0], "indices", n)==0 && nArg<3 ){
  2134   2137       struct callback_data data;
  2135   2138       char *zErrMsg = 0;
  2136   2139       open_db(p);
  2137   2140       memcpy(&data, p, sizeof(data));
................................................................................
  2772   2775     return rc;
  2773   2776   }
  2774   2777   
  2775   2778   /*
  2776   2779   ** Return TRUE if a semicolon occurs anywhere in the first N characters
  2777   2780   ** of string z[].
  2778   2781   */
  2779         -static int _contains_semicolon(const char *z, int N){
         2782  +static int line_contains_semicolon(const char *z, int N){
  2780   2783     int i;
  2781   2784     for(i=0; i<N; i++){  if( z[i]==';' ) return 1; }
  2782   2785     return 0;
  2783   2786   }
  2784   2787   
  2785   2788   /*
  2786   2789   ** Test to see if a line consists entirely of whitespace.
................................................................................
  2807   2810   }
  2808   2811   
  2809   2812   /*
  2810   2813   ** Return TRUE if the line typed in is an SQL command terminator other
  2811   2814   ** than a semi-colon.  The SQL Server style "go" command is understood
  2812   2815   ** as is the Oracle "/".
  2813   2816   */
  2814         -static int _is_command_terminator(const char *zLine){
         2817  +static int line_is_command_terminator(const char *zLine){
  2815   2818     while( IsSpace(zLine[0]) ){ zLine++; };
  2816   2819     if( zLine[0]=='/' && _all_whitespace(&zLine[1]) ){
  2817   2820       return 1;  /* Oracle */
  2818   2821     }
  2819   2822     if( ToLower(zLine[0])=='g' && ToLower(zLine[1])=='o'
  2820   2823            && _all_whitespace(&zLine[2]) ){
  2821   2824       return 1;  /* SQL Server */
................................................................................
  2823   2826     return 0;
  2824   2827   }
  2825   2828   
  2826   2829   /*
  2827   2830   ** Return true if zSql is a complete SQL statement.  Return false if it
  2828   2831   ** ends in the middle of a string literal or C-style comment.
  2829   2832   */
  2830         -static int _is_complete(char *zSql, int nSql){
         2833  +static int line_is_complete(char *zSql, int nSql){
  2831   2834     int rc;
  2832   2835     if( zSql==0 ) return 1;
  2833   2836     zSql[nSql] = ';';
  2834   2837     zSql[nSql+1] = 0;
  2835   2838     rc = sqlite3_complete(zSql);
  2836   2839     zSql[nSql] = 0;
  2837   2840     return rc;
................................................................................
  2843   2846   ** is coming from a file or device.  A prompt is issued and history
  2844   2847   ** is saved only if input is interactive.  An interrupt signal will
  2845   2848   ** cause this routine to exit immediately, unless input is interactive.
  2846   2849   **
  2847   2850   ** Return the number of errors.
  2848   2851   */
  2849   2852   static int process_input(struct callback_data *p, FILE *in){
  2850         -  char *zLine = 0;
  2851         -  char *zSql = 0;
  2852         -  int nSql = 0;
  2853         -  int nSqlPrior = 0;
  2854         -  char *zErrMsg;
  2855         -  int rc;
  2856         -  int errCnt = 0;
  2857         -  int lineno = 0;
  2858         -  int startline = 0;
         2853  +  char *zLine = 0;          /* A single input line */
         2854  +  char *zSql = 0;           /* Accumulated SQL text */
         2855  +  int nLine;                /* Length of current line */
         2856  +  int nSql = 0;             /* Bytes of zSql[] used */
         2857  +  int nAlloc = 0;           /* Allocated zSql[] space */
         2858  +  int nSqlPrior = 0;        /* Bytes of zSql[] used by prior line */
         2859  +  char *zErrMsg;            /* Error message returned */
         2860  +  int rc;                   /* Error code */
         2861  +  int errCnt = 0;           /* Number of errors seen */
         2862  +  int lineno = 0;           /* Current line number */
         2863  +  int startline = 0;        /* Line number for start of current input */
  2859   2864   
  2860   2865     while( errCnt==0 || !bail_on_error || (in==0 && stdin_is_interactive) ){
  2861   2866       fflush(p->out);
  2862         -    free(zLine);
  2863         -    zLine = one_input_line(zSql, in);
         2867  +    zLine = one_input_line(in, zLine, nSql>0);
  2864   2868       if( zLine==0 ){
  2865   2869         /* End of input */
  2866   2870         if( stdin_is_interactive ) printf("\n");
  2867   2871         break;
  2868   2872       }
  2869   2873       if( seenInterrupt ){
  2870   2874         if( in!=0 ) break;
  2871   2875         seenInterrupt = 0;
  2872   2876       }
  2873   2877       lineno++;
  2874         -    if( (zSql==0 || zSql[0]==0) && _all_whitespace(zLine) ) continue;
         2878  +    if( nSql==0 && _all_whitespace(zLine) ) continue;
  2875   2879       if( zLine && zLine[0]=='.' && nSql==0 ){
  2876   2880         if( p->echoOn ) printf("%s\n", zLine);
  2877   2881         rc = do_meta_command(zLine, p);
  2878   2882         if( rc==2 ){ /* exit requested */
  2879   2883           break;
  2880   2884         }else if( rc ){
  2881   2885           errCnt++;
  2882   2886         }
  2883   2887         continue;
  2884   2888       }
  2885         -    if( _is_command_terminator(zLine) && _is_complete(zSql, nSql) ){
         2889  +    if( line_is_command_terminator(zLine) && line_is_complete(zSql, nSql) ){
  2886   2890         memcpy(zLine,";",2);
         2891  +    }
         2892  +    nLine = strlen30(zLine);
         2893  +    if( nSql+nLine+2>=nAlloc ){
         2894  +      nAlloc = nSql+nLine+100;
         2895  +      zSql = realloc(zSql, nAlloc);
         2896  +      if( zSql==0 ){
         2897  +        fprintf(stderr, "Error: out of memory\n");
         2898  +        exit(1);
         2899  +      }
  2887   2900       }
  2888   2901       nSqlPrior = nSql;
  2889         -    if( zSql==0 ){
         2902  +    if( nSql==0 ){
  2890   2903         int i;
  2891   2904         for(i=0; zLine[i] && IsSpace(zLine[i]); i++){}
  2892         -      if( zLine[i]!=0 ){
  2893         -        nSql = strlen30(zLine);
  2894         -        zSql = malloc( nSql+3 );
  2895         -        if( zSql==0 ){
  2896         -          fprintf(stderr, "Error: out of memory\n");
  2897         -          exit(1);
  2898         -        }
  2899         -        memcpy(zSql, zLine, nSql+1);
  2900         -        startline = lineno;
  2901         -      }
         2905  +      memcpy(zSql, zLine+i, nLine+1-i);
         2906  +      startline = lineno;
         2907  +      nSql = nLine-i;
  2902   2908       }else{
  2903         -      int len = strlen30(zLine);
  2904         -      zSql = realloc( zSql, nSql + len + 4 );
  2905         -      if( zSql==0 ){
  2906         -        fprintf(stderr,"Error: out of memory\n");
  2907         -        exit(1);
  2908         -      }
  2909   2909         zSql[nSql++] = '\n';
  2910         -      memcpy(&zSql[nSql], zLine, len+1);
  2911         -      nSql += len;
         2910  +      memcpy(zSql+nSql, zLine, nLine+1);
         2911  +      nSql += nLine;
  2912   2912       }
  2913         -    if( zSql && _contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
         2913  +    if( nSql && line_contains_semicolon(&zSql[nSqlPrior], nSql-nSqlPrior)
  2914   2914                   && sqlite3_complete(zSql) ){
  2915   2915         p->cnt = 0;
  2916   2916         open_db(p);
  2917   2917         BEGIN_TIMER;
  2918   2918         rc = shell_exec(p->db, zSql, shell_callback, p, &zErrMsg);
  2919   2919         END_TIMER;
  2920   2920         if( rc || zErrMsg ){
................................................................................
  2930   2930             sqlite3_free(zErrMsg);
  2931   2931             zErrMsg = 0;
  2932   2932           }else{
  2933   2933             fprintf(stderr, "%s %s\n", zPrefix, sqlite3_errmsg(p->db));
  2934   2934           }
  2935   2935           errCnt++;
  2936   2936         }
  2937         -      free(zSql);
  2938         -      zSql = 0;
  2939   2937         nSql = 0;
  2940         -    }else if( zSql && _all_whitespace(zSql) ){
  2941         -      free(zSql);
  2942         -      zSql = 0;
         2938  +    }else if( nSql && _all_whitespace(zSql) ){
  2943   2939         nSql = 0;
  2944   2940       }
  2945   2941     }
  2946         -  if( zSql ){
         2942  +  if( nSql ){
  2947   2943       if( !_all_whitespace(zSql) ){
  2948   2944         fprintf(stderr, "Error: incomplete SQL: %s\n", zSql);
  2949   2945       }
  2950   2946       free(zSql);
  2951   2947     }
  2952   2948     free(zLine);
  2953   2949     return errCnt>0;

Changes to src/sqlite.h.in.

   469    469   #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
   470    470   #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
   471    471   #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
   472    472   #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
   473    473   #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
   474    474   #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
   475    475   #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
          476  +#define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
   476    477   #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
   477    478   #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
   478    479   #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
   479    480   #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
   480    481   #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
   481    482   #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
   482    483   #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
................................................................................
  2552   2553   ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2553   2554   ** database connection D.  An example use for this
  2554   2555   ** interface is to keep a GUI updated during a large query.
  2555   2556   **
  2556   2557   ** ^The parameter P is passed through as the only parameter to the 
  2557   2558   ** callback function X.  ^The parameter N is the approximate number of 
  2558   2559   ** [virtual machine instructions] that are evaluated between successive
  2559         -** invocations of the callback X.
         2560  +** invocations of the callback X.  ^If N is less than one then the progress
         2561  +** handler is disabled.
  2560   2562   **
  2561   2563   ** ^Only a single progress handler may be defined at one time per
  2562   2564   ** [database connection]; setting a new progress handler cancels the
  2563   2565   ** old one.  ^Setting parameter X to NULL disables the progress handler.
  2564   2566   ** ^The progress handler is also disabled by setting N to a value less
  2565   2567   ** than 1.
  2566   2568   **
................................................................................
  6258   6260   ** transaction rollback or database recovery operations are not included.
  6259   6261   ** If an IO or other error occurs while writing a page to disk, the effect
  6260   6262   ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6261   6263   ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6262   6264   ** </dd>
  6263   6265   **
  6264   6266   ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6265         -** <dd>This parameter returns the zero for the current value if and only if
  6266         -** there all foreign key constraints (deferred or immediate) have been
  6267         -** resolved.  The highwater mark is always 0.
         6267  +** <dd>This parameter returns zero for the current value if and only if
         6268  +** all foreign key constraints (deferred or immediate) have been
         6269  +** resolved.)^  ^The highwater mark is always 0.
  6268   6270   ** </dd>
  6269   6271   ** </dl>
  6270   6272   */
  6271   6273   #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
  6272   6274   #define SQLITE_DBSTATUS_CACHE_USED           1
  6273   6275   #define SQLITE_DBSTATUS_SCHEMA_USED          2
  6274   6276   #define SQLITE_DBSTATUS_STMT_USED            3
................................................................................
  7222   7224   #ifdef SQLITE_OMIT_FLOATING_POINT
  7223   7225   # undef double
  7224   7226   #endif
  7225   7227   
  7226   7228   #ifdef __cplusplus
  7227   7229   }  /* End of the 'extern "C"' block */
  7228   7230   #endif
  7229         -#endif
         7231  +#endif /* _SQLITE3_H_ */

Changes to src/sqliteInt.h.

   157    157   **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
   158    158   **
   159    159   ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
   160    160   ** assert() macro is enabled, each call into the Win32 native heap subsystem
   161    161   ** will cause HeapValidate to be called.  If heap validation should fail, an
   162    162   ** assertion will be triggered.
   163    163   **
   164         -** (Historical note:  There used to be several other options, but we've
   165         -** pared it down to just these three.)
   166         -**
   167    164   ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
   168    165   ** the default.
   169    166   */
   170    167   #if defined(SQLITE_SYSTEM_MALLOC) \
   171    168     + defined(SQLITE_WIN32_MALLOC) \
   172    169     + defined(SQLITE_ZERO_MALLOC) \
   173    170     + defined(SQLITE_MEMDEBUG)>1
................................................................................
   197    194   ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
   198    195   ** it.
   199    196   */
   200    197   #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
   201    198   #  define _XOPEN_SOURCE 600
   202    199   #endif
   203    200   
   204         -/*
   205         -** The TCL headers are only needed when compiling the TCL bindings.
   206         -*/
   207         -#if defined(SQLITE_TCL) || defined(TCLSH)
   208         -# include <tcl.h>
   209         -#endif
   210         -
   211    201   /*
   212    202   ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
   213    203   ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
   214    204   ** make it true by defining or undefining NDEBUG.
   215    205   **
   216         -** Setting NDEBUG makes the code smaller and run faster by disabling the
   217         -** number assert() statements in the code.  So we want the default action
          206  +** Setting NDEBUG makes the code smaller and faster by disabling the
          207  +** assert() statements in the code.  So we want the default action
   218    208   ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
   219    209   ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
   220    210   ** feature.
   221    211   */
   222    212   #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
   223    213   # define NDEBUG 1
   224    214   #endif
................................................................................
   280    270   ** of SQLite to unexpected behavior - to make the code "self-healing"
   281    271   ** or "ductile" rather than being "brittle" and crashing at the first
   282    272   ** hint of unplanned behavior.
   283    273   **
   284    274   ** In other words, ALWAYS and NEVER are added for defensive code.
   285    275   **
   286    276   ** When doing coverage testing ALWAYS and NEVER are hard-coded to
   287         -** be true and false so that the unreachable code then specify will
          277  +** be true and false so that the unreachable code they specify will
   288    278   ** not be counted as untested code.
   289    279   */
   290    280   #if defined(SQLITE_COVERAGE_TEST)
   291    281   # define ALWAYS(X)      (1)
   292    282   # define NEVER(X)       (0)
   293    283   #elif !defined(NDEBUG)
   294    284   # define ALWAYS(X)      ((X)?1:(assert(0),0))
................................................................................
   304    294   ** macros to verify that we have tested SQLite for large-file support.
   305    295   */
   306    296   #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
   307    297   
   308    298   /*
   309    299   ** The macro unlikely() is a hint that surrounds a boolean
   310    300   ** expression that is usually false.  Macro likely() surrounds
   311         -** a boolean expression that is usually true.  GCC is able to
   312         -** use these hints to generate better code, sometimes.
          301  +** a boolean expression that is usually true.  These hints could,
          302  +** in theory, be used by the compiler to generate better code, but
          303  +** currently they are just comments for human readers.
   313    304   */
   314         -#if defined(__GNUC__) && 0
   315         -# define likely(X)    __builtin_expect((X),1)
   316         -# define unlikely(X)  __builtin_expect((X),0)
   317         -#else
   318         -# define likely(X)    !!(X)
   319         -# define unlikely(X)  !!(X)
   320         -#endif
          305  +#define likely(X)    (X)
          306  +#define unlikely(X)  (X)
   321    307   
   322    308   #include "sqlite3.h"
   323    309   #include "hash.h"
   324    310   #include "parse.h"
   325    311   #include <stdio.h>
   326    312   #include <stdlib.h>
   327    313   #include <string.h>
................................................................................
  1474   1460   #define OE_Default  99  /* Do whatever the default action is */
  1475   1461   
  1476   1462   
  1477   1463   /*
  1478   1464   ** An instance of the following structure is passed as the first
  1479   1465   ** argument to sqlite3VdbeKeyCompare and is used to control the 
  1480   1466   ** comparison of the two index keys.
         1467  +**
         1468  +** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
         1469  +** are nField slots for the columns of an index then one extra slot
         1470  +** for the rowid at the end.
  1481   1471   */
  1482   1472   struct KeyInfo {
  1483   1473     sqlite3 *db;        /* The database connection */
  1484   1474     u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
  1485         -  u16 nField;         /* Number of entries in aColl[] */
  1486         -  u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
         1475  +  u16 nField;         /* Maximum index for aColl[] and aSortOrder[] */
         1476  +  u8 *aSortOrder;     /* Sort order for each column. */
  1487   1477     CollSeq *aColl[1];  /* Collating sequence for each term of the key */
  1488   1478   };
  1489   1479   
  1490   1480   /*
  1491   1481   ** An instance of the following structure holds information about a
  1492   1482   ** single index record that has already been parsed out into individual
  1493   1483   ** values.
................................................................................
  1548   1538     tRowcnt *aiRowEst;       /* From ANALYZE: Est. rows selected by each column */
  1549   1539     Table *pTable;           /* The SQL table being indexed */
  1550   1540     char *zColAff;           /* String defining the affinity of each column */
  1551   1541     Index *pNext;            /* The next index associated with the same table */
  1552   1542     Schema *pSchema;         /* Schema containing this index */
  1553   1543     u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
  1554   1544     char **azColl;           /* Array of collation sequence names for index */
         1545  +  Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
  1555   1546     int tnum;                /* DB Page containing root of this index */
  1556   1547     u16 nColumn;             /* Number of columns in table used by this index */
  1557   1548     u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  1558   1549     unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  1559   1550     unsigned bUnordered:1;   /* Use this index for == or IN queries only */
  1560   1551     unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
  1561   1552   #ifdef SQLITE_ENABLE_STAT3
................................................................................
  2028   2019   */
  2029   2020   #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
  2030   2021   #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
  2031   2022   #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
  2032   2023   #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
  2033   2024   #define NC_AsMaybe   0x10    /* Resolve to AS terms of the result set only
  2034   2025                                ** if no other resolution is available */
         2026  +#define NC_PartIdx   0x20    /* True if resolving a partial index WHERE */
  2035   2027   
  2036   2028   /*
  2037   2029   ** An instance of the following structure contains all information
  2038   2030   ** needed to generate code for a single SELECT statement.
  2039   2031   **
  2040   2032   ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
  2041   2033   ** If there is a LIMIT clause, the parser sets nLimit to the value of the
................................................................................
  2082   2074   #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
  2083   2075   #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
  2084   2076   #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
  2085   2077   #define SF_UseSorter       0x0040  /* Sort using a sorter */
  2086   2078   #define SF_Values          0x0080  /* Synthesized from VALUES clause */
  2087   2079   #define SF_Materialize     0x0100  /* Force materialization of views */
  2088   2080   #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
         2081  +#define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
  2089   2082   
  2090   2083   
  2091   2084   /*
  2092   2085   ** The results of a select can be distributed in several ways.  The
  2093   2086   ** "SRT" prefix means "SELECT Result Type".
  2094   2087   */
  2095   2088   #define SRT_Union        1  /* Store result as keys in an index */
................................................................................
  2203   2196     u8 nested;           /* Number of nested calls to the parser/code generator */
  2204   2197     u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
  2205   2198     u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
  2206   2199     u8 nColCache;        /* Number of entries in aColCache[] */
  2207   2200     u8 iColCache;        /* Next entry in aColCache[] to replace */
  2208   2201     u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
  2209   2202     u8 mayAbort;         /* True if statement may throw an ABORT exception */
         2203  +  u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
  2210   2204     int aTempReg[8];     /* Holding area for temporary registers */
  2211   2205     int nRangeReg;       /* Size of the temporary register block */
  2212   2206     int iRangeReg;       /* First register in temporary register block */
  2213   2207     int nErr;            /* Number of errors seen */
  2214   2208     int nTab;            /* Number of previously allocated VDBE cursors */
  2215   2209     int nMem;            /* Number of memory cells used so far */
  2216   2210     int nSet;            /* Number of sets used so far */
  2217   2211     int nOnce;           /* Number of OP_Once instructions so far */
  2218   2212     int ckBase;          /* Base register of data during check constraints */
         2213  +  int iPartIdxTab;     /* Table corresponding to a partial index */
  2219   2214     int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  2220   2215     int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
  2221   2216     struct yColCache {
  2222   2217       int iTable;           /* Table cursor number */
  2223   2218       int iColumn;          /* Table column number */
  2224   2219       u8 tempReg;           /* iReg is a temp register that needs to be freed */
  2225   2220       int iLevel;           /* Nesting level */
................................................................................
  2793   2788   void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  2794   2789   int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  2795   2790   void sqlite3SrcListShiftJoinType(SrcList*);
  2796   2791   void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  2797   2792   void sqlite3IdListDelete(sqlite3*, IdList*);
  2798   2793   void sqlite3SrcListDelete(sqlite3*, SrcList*);
  2799   2794   Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  2800         -                        Token*, int, int);
         2795  +                          Expr*, int, int);
  2801   2796   void sqlite3DropIndex(Parse*, SrcList*, int);
  2802   2797   int sqlite3Select(Parse*, Select*, SelectDest*);
  2803   2798   Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  2804   2799                            Expr*,ExprList*,u16,Expr*,Expr*);
  2805   2800   void sqlite3SelectDelete(sqlite3*, Select*);
  2806   2801   Table *sqlite3SrcListLookup(Parse*, SrcList*);
  2807   2802   int sqlite3IsReadOnly(Parse*, Table*, int);
................................................................................
  2841   2836   Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  2842   2837   Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  2843   2838   void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  2844   2839   void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  2845   2840   void sqlite3Vacuum(Parse*);
  2846   2841   int sqlite3RunVacuum(char**, sqlite3*);
  2847   2842   char *sqlite3NameFromToken(sqlite3*, Token*);
  2848         -int sqlite3ExprCompare(Expr*, Expr*);
  2849         -int sqlite3ExprListCompare(ExprList*, ExprList*);
         2843  +int sqlite3ExprCompare(Expr*, Expr*, int);
         2844  +int sqlite3ExprListCompare(ExprList*, ExprList*, int);
         2845  +int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  2850   2846   void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  2851   2847   void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  2852   2848   int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  2853   2849   Vdbe *sqlite3GetVdbe(Parse*);
  2854   2850   void sqlite3PrngSaveState(void);
  2855   2851   void sqlite3PrngRestoreState(void);
  2856   2852   void sqlite3PrngResetState(void);
................................................................................
  2869   2865   int sqlite3ExprIsInteger(Expr*, int*);
  2870   2866   int sqlite3ExprCanBeNull(const Expr*);
  2871   2867   void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  2872   2868   int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  2873   2869   int sqlite3IsRowid(const char*);
  2874   2870   void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  2875   2871   void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  2876         -int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
         2872  +int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
  2877   2873   void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  2878   2874                                        int*,int,int,int,int,int*);
  2879   2875   void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  2880   2876   int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  2881   2877   void sqlite3BeginWriteOperation(Parse*, int, int);
  2882   2878   void sqlite3MultiWrite(Parse*);
  2883   2879   void sqlite3MayAbort(Parse*);
................................................................................
  3072   3068   void sqlite3NestedParse(Parse*, const char*, ...);
  3073   3069   void sqlite3ExpirePreparedStatements(sqlite3*);
  3074   3070   int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  3075   3071   void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  3076   3072   int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  3077   3073   int sqlite3ResolveExprNames(NameContext*, Expr*);
  3078   3074   void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
         3075  +void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  3079   3076   int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  3080   3077   void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  3081   3078   void sqlite3AlterFinishAddColumn(Parse *, Token *);
  3082   3079   void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  3083   3080   CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  3084   3081   char sqlite3AffinityType(const char*);
  3085   3082   void sqlite3Analyze(Parse*, Token*, Token*);
................................................................................
  3091   3088   void sqlite3DefaultRowEst(Index*);
  3092   3089   void sqlite3RegisterLikeFunctions(sqlite3*, int);
  3093   3090   int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  3094   3091   void sqlite3MinimumFileFormat(Parse*, int, int);
  3095   3092   void sqlite3SchemaClear(void *);
  3096   3093   Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  3097   3094   int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
         3095  +KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int);
  3098   3096   KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  3099   3097   int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
  3100   3098     void (*)(sqlite3_context*,int,sqlite3_value **),
  3101   3099     void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  3102   3100     FuncDestructor *pDestructor
  3103   3101   );
  3104   3102   int sqlite3ApiExit(sqlite3 *db, int);

Changes to src/test_autoext.c.

   204    204   #ifndef SQLITE_OMIT_LOAD_EXTENSION
   205    205     Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_sqr",
   206    206             autoExtSqrObjCmd, 0, 0);
   207    207     Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_cube",
   208    208             autoExtCubeObjCmd, 0, 0);
   209    209     Tcl_CreateObjCommand(interp, "sqlite3_auto_extension_broken",
   210    210             autoExtBrokenObjCmd, 0, 0);
   211         -#endif
   212    211     Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_sqr",
   213    212             cancelAutoExtSqrObjCmd, 0, 0);
   214    213     Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_cube",
   215    214             cancelAutoExtCubeObjCmd, 0, 0);
   216    215     Tcl_CreateObjCommand(interp, "sqlite3_cancel_auto_extension_broken",
   217    216             cancelAutoExtBrokenObjCmd, 0, 0);
          217  +#endif
   218    218     Tcl_CreateObjCommand(interp, "sqlite3_reset_auto_extension",
   219    219             resetAutoExtObjCmd, 0, 0);
   220    220     return TCL_OK;
   221    221   }

Changes to src/test_demovfs.c.

   532    532     int nPathOut,                   /* Size of output buffer in bytes */
   533    533     char *zPathOut                  /* Pointer to output buffer */
   534    534   ){
   535    535     char zDir[MAXPATHNAME+1];
   536    536     if( zPath[0]=='/' ){
   537    537       zDir[0] = '\0';
   538    538     }else{
   539         -    getcwd(zDir, sizeof(zDir));
          539  +    if( getcwd(zDir, sizeof(zDir))==0 ) return SQLITE_IOERR;
   540    540     }
   541    541     zDir[MAXPATHNAME] = '\0';
   542    542   
   543    543     sqlite3_snprintf(nPathOut, zPathOut, "%s/%s", zDir, zPath);
   544    544     zPathOut[nPathOut-1] = '\0';
   545    545   
   546    546     return SQLITE_OK;

Changes to src/test_fs.c.

   191    191     assert( i==0 || i==1 );
   192    192     if( i==0 ){
   193    193       sqlite3_result_value(ctx, sqlite3_column_value(pCur->pStmt, 0));
   194    194     }else{
   195    195       const char *zFile = (const char *)sqlite3_column_text(pCur->pStmt, 1);
   196    196       struct stat sbuf;
   197    197       int fd;
          198  +    int n;
   198    199   
   199    200       fd = open(zFile, O_RDONLY);
   200    201       if( fd<0 ) return SQLITE_IOERR;
   201    202       fstat(fd, &sbuf);
   202    203   
   203    204       if( sbuf.st_size>=pCur->nAlloc ){
   204    205         int nNew = sbuf.st_size*2;
................................................................................
   210    211           close(fd);
   211    212           return SQLITE_NOMEM;
   212    213         }
   213    214         pCur->zBuf = zNew;
   214    215         pCur->nAlloc = nNew;
   215    216       }
   216    217   
   217         -    read(fd, pCur->zBuf, sbuf.st_size);
          218  +    n = (int)read(fd, pCur->zBuf, sbuf.st_size);
   218    219       close(fd);
          220  +    if( n!=sbuf.st_size ) return SQLITE_ERROR;
   219    221       pCur->nBuf = sbuf.st_size;
   220    222       pCur->zBuf[pCur->nBuf] = '\0';
   221    223   
   222    224       sqlite3_result_text(ctx, pCur->zBuf, -1, SQLITE_TRANSIENT);
   223    225     }
   224    226     return SQLITE_OK;
   225    227   }

Changes to src/test_intarray.h.

    71     71   ** The intarray object is automatically destroyed when its corresponding
    72     72   ** virtual table is dropped.  Since the virtual tables are created in the
    73     73   ** TEMP database, they are automatically dropped when the database connection
    74     74   ** closes so the application does not normally need to take any special
    75     75   ** action to free the intarray objects.
    76     76   */
    77     77   #include "sqlite3.h"
           78  +#ifndef _INTARRAY_H_
           79  +#define _INTARRAY_H_
    78     80   
    79     81   /*
    80     82   ** Make sure we can call this stuff from C++.
    81     83   */
    82     84   #ifdef __cplusplus
    83     85   extern "C" {
    84     86   #endif
................................................................................
   119    121     sqlite3_int64 *aElements,      /* Content of the intarray */
   120    122     void (*xFree)(void*)           /* How to dispose of the intarray when done */
   121    123   );
   122    124   
   123    125   #ifdef __cplusplus
   124    126   }  /* End of the 'extern "C"' block */
   125    127   #endif
          128  +#endif /* _INTARRAY_H_ */

Changes to src/test_multiplex.h.

    92     92   */
    93     93   extern int sqlite3_multiplex_shutdown(void);
    94     94   
    95     95   #ifdef __cplusplus
    96     96   }  /* End of the 'extern "C"' block */
    97     97   #endif
    98     98   
    99         -#endif
           99  +#endif /* _TEST_MULTIPLEX_H */

Changes to src/test_rtree.c.

    10     10   **
    11     11   *************************************************************************
    12     12   ** Code for testing all sorts of SQLite interfaces. This code
    13     13   ** is not included in the SQLite library. 
    14     14   */
    15     15   
    16     16   #include <sqlite3.h>
           17  +#include <tcl.h>
    17     18   
    18     19   /* Solely for the UNUSED_PARAMETER() macro. */
    19     20   #include "sqliteInt.h"
    20     21   
    21     22   #ifdef SQLITE_ENABLE_RTREE
    22     23   /* 
    23     24   ** Type used to cache parameter information for the "circle" r-tree geometry

Changes to src/test_vfs.c.

    24     24   **   -mxpathname INTEGER        (Value for sqlite3_vfs.mxPathname)
    25     25   **   -iversion   INTEGER        (Value for sqlite3_vfs.iVersion)
    26     26   */
    27     27   #if SQLITE_TEST          /* This file is used for testing only */
    28     28   
    29     29   #include "sqlite3.h"
    30     30   #include "sqliteInt.h"
           31  +#include <tcl.h>
    31     32   
    32     33   typedef struct Testvfs Testvfs;
    33     34   typedef struct TestvfsShm TestvfsShm;
    34     35   typedef struct TestvfsBuffer TestvfsBuffer;
    35     36   typedef struct TestvfsFile TestvfsFile;
    36     37   typedef struct TestvfsFd TestvfsFd;
    37     38   

Changes to src/tokenize.c.

   119    119         testcase( z[0]=='\r' );
   120    120         for(i=1; sqlite3Isspace(z[i]); i++){}
   121    121         *tokenType = TK_SPACE;
   122    122         return i;
   123    123       }
   124    124       case '-': {
   125    125         if( z[1]=='-' ){
   126         -        /* IMP: R-50417-27976 -- syntax diagram for comments */
   127    126           for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
   128    127           *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   129    128           return i;
   130    129         }
   131    130         *tokenType = TK_MINUS;
   132    131         return 1;
   133    132       }
................................................................................
   152    151         return 1;
   153    152       }
   154    153       case '/': {
   155    154         if( z[1]!='*' || z[2]==0 ){
   156    155           *tokenType = TK_SLASH;
   157    156           return 1;
   158    157         }
   159         -      /* IMP: R-50417-27976 -- syntax diagram for comments */
   160    158         for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
   161    159         if( c ) i++;
   162    160         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
   163    161         return i;
   164    162       }
   165    163       case '%': {
   166    164         *tokenType = TK_REM;

Changes to src/update.c.

   242    242     for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
   243    243     if( nIdx>0 ){
   244    244       aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
   245    245       if( aRegIdx==0 ) goto update_cleanup;
   246    246     }
   247    247     for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
   248    248       int reg;
   249         -    if( hasFK || chngRowid ){
          249  +    if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
   250    250         reg = ++pParse->nMem;
   251    251       }else{
   252    252         reg = 0;
   253    253         for(i=0; i<pIdx->nColumn; i++){
   254    254           if( aXRef[pIdx->aiColumn[i]]>=0 ){
   255    255             reg = ++pParse->nMem;
   256    256             break;

Changes to src/vdbe.c.

   551    551     int rc = SQLITE_OK;        /* Value to return */
   552    552     sqlite3 *db = p->db;       /* The database */
   553    553     u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
   554    554     u8 encoding = ENC(db);     /* The database encoding */
   555    555     int iCompare = 0;          /* Result of last OP_Compare operation */
   556    556     unsigned nVmStep = 0;      /* Number of virtual machine steps */
   557    557   #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   558         -  unsigned nProgressOps = 0; /* nVmStep at last progress callback. */
          558  +  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
   559    559   #endif
   560    560     Mem *aMem = p->aMem;       /* Copy of p->aMem */
   561    561     Mem *pIn1 = 0;             /* 1st input operand */
   562    562     Mem *pIn2 = 0;             /* 2nd input operand */
   563    563     Mem *pIn3 = 0;             /* 3rd input operand */
   564    564     Mem *pOut = 0;             /* Output operand */
   565    565     int *aPermute = 0;         /* Permutation of columns for OP_Compare */
................................................................................
   581    581     assert( p->bIsReader || p->readOnly!=0 );
   582    582     p->rc = SQLITE_OK;
   583    583     assert( p->explain==0 );
   584    584     p->pResultSet = 0;
   585    585     db->busyHandler.nBusy = 0;
   586    586     CHECK_FOR_INTERRUPT;
   587    587     sqlite3VdbeIOTraceSql(p);
          588  +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
          589  +  if( db->xProgress ){
          590  +    assert( 0 < db->nProgressOps );
          591  +    nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP-1];
          592  +    if( nProgressLimit==0 ){
          593  +      nProgressLimit = db->nProgressOps;
          594  +    }else{
          595  +      nProgressLimit %= (unsigned)db->nProgressOps;
          596  +    }
          597  +  }
          598  +#endif
   588    599   #ifdef SQLITE_DEBUG
   589    600     sqlite3BeginBenignMalloc();
   590    601     if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
   591    602       int i;
   592    603       printf("VDBE Program Listing:\n");
   593    604       sqlite3VdbePrintSql(p);
   594    605       for(i=0; i<p->nOp; i++){
................................................................................
   741    752   #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
   742    753     /* Call the progress callback if it is configured and the required number
   743    754     ** of VDBE ops have been executed (either since this invocation of
   744    755     ** sqlite3VdbeExec() or since last time the progress callback was called).
   745    756     ** If the progress callback returns non-zero, exit the virtual machine with
   746    757     ** a return code SQLITE_ABORT.
   747    758     */
   748         -  if( db->xProgress!=0 && (nVmStep - nProgressOps)>=db->nProgressOps ){
          759  +  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
   749    760       int prc;
   750    761       prc = db->xProgress(db->pProgressArg);
   751    762       if( prc!=0 ){
   752    763         rc = SQLITE_INTERRUPT;
   753    764         goto vdbe_error_halt;
   754    765       }
   755         -    nProgressOps = nVmStep;
          766  +    if( db->xProgress!=0 ){
          767  +      nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
          768  +    }
   756    769     }
   757    770   #endif
   758    771     
   759    772     break;
   760    773   }
   761    774   
   762    775   /* Opcode:  Gosub P1 P2 * * *

Changes to src/vdbe.h.

   200    200   void sqlite3VdbeSetNumCols(Vdbe*,int);
   201    201   int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
   202    202   void sqlite3VdbeCountChanges(Vdbe*);
   203    203   sqlite3 *sqlite3VdbeDb(Vdbe*);
   204    204   void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
   205    205   void sqlite3VdbeSwap(Vdbe*,Vdbe*);
   206    206   VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
   207         -sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
          207  +sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
   208    208   void sqlite3VdbeSetVarmask(Vdbe*, int);
   209    209   #ifndef SQLITE_OMIT_TRACE
   210    210     char *sqlite3VdbeExpandSql(Vdbe*, const char*);
   211    211   #endif
   212    212   
   213    213   void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
   214    214   int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);

Changes to src/vdbeaux.c.

   246    246   ** Resolve label "x" to be the address of the next instruction to
   247    247   ** be inserted.  The parameter "x" must have been obtained from
   248    248   ** a prior call to sqlite3VdbeMakeLabel().
   249    249   */
   250    250   void sqlite3VdbeResolveLabel(Vdbe *p, int x){
   251    251     int j = -1-x;
   252    252     assert( p->magic==VDBE_MAGIC_INIT );
   253         -  assert( j>=0 && j<p->nLabel );
   254         -  if( p->aLabel ){
          253  +  assert( j<p->nLabel );
          254  +  if( j>=0 && p->aLabel ){
   255    255       p->aLabel[j] = p->nOp;
   256    256     }
   257    257   }
   258    258   
   259    259   /*
   260    260   ** Mark the VDBE as one that can only be run one time.
   261    261   */
................................................................................
   403    403     Op *pOp;
   404    404     int *aLabel = p->aLabel;
   405    405     p->readOnly = 1;
   406    406     p->bIsReader = 0;
   407    407     for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
   408    408       u8 opcode = pOp->opcode;
   409    409   
   410         -    pOp->opflags = sqlite3OpcodeProperty[opcode];
   411         -    if( opcode==OP_Function || opcode==OP_AggStep ){
   412         -      if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
   413         -    }else if( opcode==OP_Transaction ){
   414         -      if( pOp->p2!=0 ) p->readOnly = 0;
   415         -      p->bIsReader = 1;
   416         -    }else if( opcode==OP_AutoCommit || opcode==OP_Savepoint ){
   417         -      p->bIsReader = 1;
   418         -    }else if( opcode==OP_Vacuum
   419         -           || opcode==OP_JournalMode
          410  +    /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
          411  +    ** cases from this switch! */
          412  +    switch( opcode ){
          413  +      case OP_Function:
          414  +      case OP_AggStep: {
          415  +        if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
          416  +        break;
          417  +      }
          418  +      case OP_Transaction: {
          419  +        if( pOp->p2!=0 ) p->readOnly = 0;
          420  +        /* fall thru */
          421  +      }
          422  +      case OP_AutoCommit:
          423  +      case OP_Savepoint: {
          424  +        p->bIsReader = 1;
          425  +        break;
          426  +      }
   420    427   #ifndef SQLITE_OMIT_WAL
   421         -           || opcode==OP_Checkpoint
          428  +      case OP_Checkpoint:
   422    429   #endif
   423         -    ){
   424         -      p->readOnly = 0;
   425         -      p->bIsReader = 1;
          430  +      case OP_Vacuum:
          431  +      case OP_JournalMode: {
          432  +        p->readOnly = 0;
          433  +        p->bIsReader = 1;
          434  +        break;
          435  +      }
   426    436   #ifndef SQLITE_OMIT_VIRTUALTABLE
   427         -    }else if( opcode==OP_VUpdate ){
   428         -      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
   429         -    }else if( opcode==OP_VFilter ){
   430         -      int n;
   431         -      assert( p->nOp - i >= 3 );
   432         -      assert( pOp[-1].opcode==OP_Integer );
   433         -      n = pOp[-1].p1;
   434         -      if( n>nMaxArgs ) nMaxArgs = n;
   435         -#endif
   436         -    }else if( opcode==OP_Next || opcode==OP_SorterNext ){
   437         -      pOp->p4.xAdvance = sqlite3BtreeNext;
   438         -      pOp->p4type = P4_ADVANCE;
   439         -    }else if( opcode==OP_Prev ){
   440         -      pOp->p4.xAdvance = sqlite3BtreePrevious;
   441         -      pOp->p4type = P4_ADVANCE;
   442         -    }
   443         -
          437  +      case OP_VUpdate: {
          438  +        if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
          439  +        break;
          440  +      }
          441  +      case OP_VFilter: {
          442  +        int n;
          443  +        assert( p->nOp - i >= 3 );
          444  +        assert( pOp[-1].opcode==OP_Integer );
          445  +        n = pOp[-1].p1;
          446  +        if( n>nMaxArgs ) nMaxArgs = n;
          447  +        break;
          448  +      }
          449  +#endif
          450  +      case OP_Next:
          451  +      case OP_SorterNext: {
          452  +        pOp->p4.xAdvance = sqlite3BtreeNext;
          453  +        pOp->p4type = P4_ADVANCE;
          454  +        break;
          455  +      }
          456  +      case OP_Prev: {
          457  +        pOp->p4.xAdvance = sqlite3BtreePrevious;
          458  +        pOp->p4type = P4_ADVANCE;
          459  +        break;
          460  +      }
          461  +    }
          462  +
          463  +    pOp->opflags = sqlite3OpcodeProperty[opcode];
   444    464       if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
   445    465         assert( -1-pOp->p2<p->nLabel );
   446    466         pOp->p2 = aLabel[-1-pOp->p2];
   447    467       }
   448    468     }
   449    469     sqlite3DbFree(p->db, p->aLabel);
   450    470     p->aLabel = 0;
................................................................................
   571    591   }
   572    592   
   573    593   /*
   574    594   ** Change the P2 operand of instruction addr so that it points to
   575    595   ** the address of the next instruction to be coded.
   576    596   */
   577    597   void sqlite3VdbeJumpHere(Vdbe *p, int addr){
   578         -  assert( addr>=0 || p->db->mallocFailed );
   579         -  if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
          598  +  if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp);
   580    599   }
   581    600   
   582    601   
   583    602   /*
   584    603   ** If the input FuncDef structure is ephemeral, then free it.  If
   585    604   ** the FuncDef is not ephermal, then do nothing.
   586    605   */
................................................................................
   726    745       ** that was cast to a (const char *). */
   727    746       pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
   728    747       pOp->p4type = P4_INT32;
   729    748     }else if( zP4==0 ){
   730    749       pOp->p4.p = 0;
   731    750       pOp->p4type = P4_NOTUSED;
   732    751     }else if( n==P4_KEYINFO ){
   733         -    KeyInfo *pKeyInfo;
   734         -    int nField, nByte;
          752  +    KeyInfo *pOrig, *pNew;
   735    753   
   736         -    nField = ((KeyInfo*)zP4)->nField;
   737         -    nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
   738         -    pKeyInfo = sqlite3DbMallocRaw(0, nByte);
   739         -    pOp->p4.pKeyInfo = pKeyInfo;
   740         -    if( pKeyInfo ){
   741         -      u8 *aSortOrder;
   742         -      memcpy((char*)pKeyInfo, zP4, nByte - nField);
   743         -      aSortOrder = pKeyInfo->aSortOrder;
   744         -      assert( aSortOrder!=0 );
   745         -      pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
   746         -      memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
          754  +    pOrig = (KeyInfo*)zP4;
          755  +    pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField);
          756  +    if( pNew ){
          757  +      memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0]));
          758  +      memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField);
   747    759         pOp->p4type = P4_KEYINFO;
   748    760       }else{
   749    761         p->db->mallocFailed = 1;
   750    762         pOp->p4type = P4_NOTUSED;
   751    763       }
   752    764     }else if( n==P4_KEYINFO_HANDOFF ){
   753    765       pOp->p4.p = (void*)zP4;
................................................................................
  2986   2998   ** equal, then the keys are considered to be equal and
  2987   2999   ** the parts beyond the common prefix are ignored.
  2988   3000   */
  2989   3001   int sqlite3VdbeRecordCompare(
  2990   3002     int nKey1, const void *pKey1, /* Left key */
  2991   3003     UnpackedRecord *pPKey2        /* Right key */
  2992   3004   ){
  2993         -  int d1;            /* Offset into aKey[] of next data element */
         3005  +  u32 d1;            /* Offset into aKey[] of next data element */
  2994   3006     u32 idx1;          /* Offset into aKey[] of next header element */
  2995   3007     u32 szHdr1;        /* Number of bytes in header */
  2996   3008     int i = 0;
  2997         -  int nField;
  2998   3009     int rc = 0;
  2999   3010     const unsigned char *aKey1 = (const unsigned char *)pKey1;
  3000   3011     KeyInfo *pKeyInfo;
  3001   3012     Mem mem1;
  3002   3013   
  3003   3014     pKeyInfo = pPKey2->pKeyInfo;
  3004   3015     mem1.enc = pKeyInfo->enc;
................................................................................
  3013   3024     ** impact, since this routine is a very high runner.  And so, we choose
  3014   3025     ** to ignore the compiler warnings and leave this variable uninitialized.
  3015   3026     */
  3016   3027     /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
  3017   3028     
  3018   3029     idx1 = getVarint32(aKey1, szHdr1);
  3019   3030     d1 = szHdr1;
  3020         -  nField = pKeyInfo->nField;
         3031  +  assert( pKeyInfo->nField+1>=pPKey2->nField );
  3021   3032     assert( pKeyInfo->aSortOrder!=0 );
  3022   3033     while( idx1<szHdr1 && i<pPKey2->nField ){
  3023   3034       u32 serial_type1;
  3024   3035   
  3025   3036       /* Read the serial types for the next element in each key. */
  3026   3037       idx1 += getVarint32( aKey1+idx1, serial_type1 );
  3027         -    if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
         3038  +
         3039  +    /* Verify that there is enough key space remaining to avoid
         3040  +    ** a buffer overread.  The "d1+serial_type1+2" subexpression will
         3041  +    ** always be greater than or equal to the amount of required key space.
         3042  +    ** Use that approximation to avoid the more expensive call to
         3043  +    ** sqlite3VdbeSerialTypeLen() in the common case.
         3044  +    */
         3045  +    if( d1+serial_type1+2>(u32)nKey1
         3046  +     && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 
         3047  +    ){
         3048  +      break;
         3049  +    }
  3028   3050   
  3029   3051       /* Extract the values to be compared.
  3030   3052       */
  3031   3053       d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  3032   3054   
  3033   3055       /* Do the comparison
  3034   3056       */
  3035         -    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  3036         -                           i<nField ? pKeyInfo->aColl[i] : 0);
         3057  +    rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  3037   3058       if( rc!=0 ){
  3038   3059         assert( mem1.zMalloc==0 );  /* See comment below */
  3039   3060   
  3040   3061         /* Invert the result if we are using DESC sort order. */
  3041         -      if( i<nField && pKeyInfo->aSortOrder[i] ){
         3062  +      if( pKeyInfo->aSortOrder[i] ){
  3042   3063           rc = -rc;
  3043   3064         }
  3044   3065       
  3045   3066         /* If the PREFIX_SEARCH flag is set and all fields except the final
  3046   3067         ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
  3047   3068         ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  3048   3069         ** This is used by the OP_IsUnique opcode.
................................................................................
  3249   3270   ** Return a pointer to an sqlite3_value structure containing the value bound
  3250   3271   ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
  3251   3272   ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  3252   3273   ** constants) to the value before returning it.
  3253   3274   **
  3254   3275   ** The returned value must be freed by the caller using sqlite3ValueFree().
  3255   3276   */
  3256         -sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
         3277  +sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  3257   3278     assert( iVar>0 );
  3258   3279     if( v ){
  3259   3280       Mem *pMem = &v->aVar[iVar-1];
  3260   3281       if( 0==(pMem->flags & MEM_Null) ){
  3261   3282         sqlite3_value *pRet = sqlite3ValueNew(v->db);
  3262   3283         if( pRet ){
  3263   3284           sqlite3VdbeMemCopy((Mem *)pRet, pMem);

Changes to src/where.c.

    29     29       && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
    30     30   # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
    31     31   # define WHERETRACE_ENABLED 1
    32     32   #else
    33     33   # define WHERETRACE(K,X)
    34     34   #endif
    35     35   
    36         -/* Forward reference
           36  +/* Forward references
    37     37   */
    38     38   typedef struct WhereClause WhereClause;
    39     39   typedef struct WhereMaskSet WhereMaskSet;
    40     40   typedef struct WhereOrInfo WhereOrInfo;
    41     41   typedef struct WhereAndInfo WhereAndInfo;
    42     42   typedef struct WhereLevel WhereLevel;
    43     43   typedef struct WhereLoop WhereLoop;
................................................................................
    51     51   /*
    52     52   ** Cost X is tracked as 10*log2(X) stored in a 16-bit integer.  The
    53     53   ** maximum cost for ordinary tables is 64*(2**63) which becomes 6900.
    54     54   ** (Virtual tables can return a larger cost, but let's assume they do not.)
    55     55   ** So all costs can be stored in a 16-bit unsigned integer without risk
    56     56   ** of overflow.
    57     57   **
    58         -** Costs are estimates, so don't go to the computational trouble to compute
    59         -** 10*log2(X) exactly.  Instead, a close estimate is used.  Any value of
    60         -** X<=1 is stored as 0.  X=2 is 10.  X=3 is 16.  X=1000 is 99. etc.
           58  +** Costs are estimates, so no effort is made to compute 10*log2(X) exactly.
           59  +** Instead, a close estimate is used.  Any value of X<=1 is stored as 0.
           60  +** X=2 is 10.  X=3 is 16.  X=1000 is 99. etc.
    61     61   **
    62     62   ** The tool/wherecosttest.c source file implements a command-line program
    63         -** that will convert between WhereCost to integers and do addition and
    64         -** multiplication on WhereCost values.  That command-line program is a
    65         -** useful utility to have around when working with this module.
           63  +** that will convert WhereCosts to integers, convert integers to WhereCosts
           64  +** and do addition and multiplication on WhereCost values.  The wherecosttest
           65  +** command-line program is a useful utility to have around when working with
           66  +** this module.
    66     67   */
    67     68   typedef unsigned short int WhereCost;
    68     69   
    69     70   /*
    70     71   ** This object contains information needed to implement a single nested
    71     72   ** loop in WHERE clause.
    72     73   **
................................................................................
   161    162   struct WhereOrCost {
   162    163     Bitmask prereq;     /* Prerequisites */
   163    164     WhereCost rRun;     /* Cost of running this subquery */
   164    165     WhereCost nOut;     /* Number of outputs for this subquery */
   165    166   };
   166    167   
   167    168   /* The WhereOrSet object holds a set of possible WhereOrCosts that
   168         -** correspond to the subquery(s) of OR-clause processing.  At most
   169         -** favorable N_OR_COST elements are retained.
          169  +** correspond to the subquery(s) of OR-clause processing.  Only the
          170  +** best N_OR_COST elements are retained.
   170    171   */
   171    172   #define N_OR_COST 3
   172    173   struct WhereOrSet {
   173    174     u16 n;                      /* Number of valid a[] entries */
   174    175     WhereOrCost a[N_OR_COST];   /* Set of best costs */
   175    176   };
   176    177   
................................................................................
   228    229   ** use of a bitmask encoding for the operator allows us to search
   229    230   ** quickly for terms that match any of several different operators.
   230    231   **
   231    232   ** A WhereTerm might also be two or more subterms connected by OR:
   232    233   **
   233    234   **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
   234    235   **
   235         -** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
          236  +** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
   236    237   ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
   237         -** is collected about the
          238  +** is collected about the OR clause.
   238    239   **
   239    240   ** If a term in the WHERE clause does not match either of the two previous
   240    241   ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
   241    242   ** to the original subexpression content and wtFlags is set up appropriately
   242    243   ** but no other fields in the WhereTerm object are meaningful.
   243    244   **
   244    245   ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
................................................................................
   654    655   ** WhereTerms.  All pointers to WhereTerms should be invalidated after
   655    656   ** calling this routine.  Such pointers may be reinitialized by referencing
   656    657   ** the pWC->a[] array.
   657    658   */
   658    659   static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
   659    660     WhereTerm *pTerm;
   660    661     int idx;
   661         -  testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
          662  +  testcase( wtFlags & TERM_VIRTUAL );
   662    663     if( pWC->nTerm>=pWC->nSlot ){
   663    664       WhereTerm *pOld = pWC->a;
   664    665       sqlite3 *db = pWC->pWInfo->pParse->db;
   665    666       pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
   666    667       if( pWC->a==0 ){
   667    668         if( wtFlags & TERM_DYNAMIC ){
   668    669           sqlite3ExprDelete(db, p);
................................................................................
   742    743   */
   743    744   static void createMask(WhereMaskSet *pMaskSet, int iCursor){
   744    745     assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
   745    746     pMaskSet->ix[pMaskSet->n++] = iCursor;
   746    747   }
   747    748   
   748    749   /*
   749         -** These routine walk (recursively) an expression tree and generates
          750  +** These routines walk (recursively) an expression tree and generate
   750    751   ** a bitmask indicating which tables are used in that expression
   751    752   ** tree.
   752    753   */
   753    754   static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
   754    755   static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
   755    756   static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
   756    757     Bitmask mask = 0;
................................................................................
   799    800     return mask;
   800    801   }
   801    802   
   802    803   /*
   803    804   ** Return TRUE if the given operator is one of the operators that is
   804    805   ** allowed for an indexable WHERE clause term.  The allowed operators are
   805    806   ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
   806         -**
   807         -** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
   808         -** of one of the following forms: column = expression column > expression
   809         -** column >= expression column < expression column <= expression
   810         -** expression = column expression > column expression >= column
   811         -** expression < column expression <= column column IN
   812         -** (expression-list) column IN (subquery) column IS NULL
   813    807   */
   814    808   static int allowedOp(int op){
   815    809     assert( TK_GT>TK_EQ && TK_GT<TK_GE );
   816    810     assert( TK_LT>TK_EQ && TK_LT<TK_GE );
   817    811     assert( TK_LE>TK_EQ && TK_LE<TK_GE );
   818    812     assert( TK_GE==TK_EQ+4 );
   819    813     return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
................................................................................
  1124   1118     op = pRight->op;
  1125   1119     if( op==TK_REGISTER ){
  1126   1120       op = pRight->op2;
  1127   1121     }
  1128   1122     if( op==TK_VARIABLE ){
  1129   1123       Vdbe *pReprepare = pParse->pReprepare;
  1130   1124       int iCol = pRight->iColumn;
  1131         -    pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
         1125  +    pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  1132   1126       if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  1133   1127         z = (char *)sqlite3_value_text(pVal);
  1134   1128       }
  1135   1129       sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  1136   1130       assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  1137   1131     }else if( op==TK_STRING ){
  1138   1132       z = pRight->u.zToken;
................................................................................
  1266   1260   ** subsubterms at least one of which is indexable.  Indexable AND 
  1267   1261   ** subterms have their eOperator set to WO_AND and they have
  1268   1262   ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  1269   1263   **
  1270   1264   ** From another point of view, "indexable" means that the subterm could
  1271   1265   ** potentially be used with an index if an appropriate index exists.
  1272   1266   ** This analysis does not consider whether or not the index exists; that
  1273         -** is something the bestIndex() routine will determine.  This analysis
  1274         -** only looks at whether subterms appropriate for indexing exist.
         1267  +** is decided elsewhere.  This analysis only looks at whether subterms
         1268  +** appropriate for indexing exist.
  1275   1269   **
  1276         -** All examples A through E above all satisfy case 2.  But if a term
         1270  +** All examples A through E above satisfy case 2.  But if a term
  1277   1271   ** also statisfies case 1 (such as B) we know that the optimizer will
  1278   1272   ** always prefer case 1, so in that case we pretend that case 2 is not
  1279   1273   ** satisfied.
  1280   1274   **
  1281   1275   ** It might be the case that multiple tables are indexable.  For example,
  1282   1276   ** (E) above is indexable on tables P, Q, and R.
  1283   1277   **
................................................................................
  1479   1473           }
  1480   1474         }
  1481   1475       }
  1482   1476   
  1483   1477       /* At this point, okToChngToIN is true if original pTerm satisfies
  1484   1478       ** case 1.  In that case, construct a new virtual term that is 
  1485   1479       ** pTerm converted into an IN operator.
  1486         -    **
  1487         -    ** EV: R-00211-15100
  1488   1480       */
  1489   1481       if( okToChngToIN ){
  1490   1482         Expr *pDup;            /* A transient duplicate expression */
  1491   1483         ExprList *pList = 0;   /* The RHS of the IN operator */
  1492   1484         Expr *pLeft = 0;       /* The LHS of the IN operator */
  1493   1485         Expr *pNew;            /* The complete IN operator */
  1494   1486   
................................................................................
  1722   1714         if( noCase ){
  1723   1715           /* The point is to increment the last character before the first
  1724   1716           ** wildcard.  But if we increment '@', that will push it into the
  1725   1717           ** alphabetic range where case conversions will mess up the 
  1726   1718           ** inequality.  To avoid this, make sure to also run the full
  1727   1719           ** LIKE on all candidate expressions by clearing the isComplete flag
  1728   1720           */
  1729         -        if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
  1730         -
  1731         -
         1721  +        if( c=='A'-1 ) isComplete = 0;
  1732   1722           c = sqlite3UpperToLower[c];
  1733   1723         }
  1734   1724         *pC = c + 1;
  1735   1725       }
  1736   1726       sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  1737   1727       sCollSeqName.n = 6;
  1738   1728       pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
................................................................................
  1940   1930       }
  1941   1931     }
  1942   1932   
  1943   1933     return 0;
  1944   1934   }
  1945   1935   
  1946   1936   /* 
  1947         -** The (an approximate) sum of two WhereCosts.  This computation is
         1937  +** Find (an approximate) sum of two WhereCosts.  This computation is
  1948   1938   ** not a simple "+" operator because WhereCost is stored as a logarithmic
  1949   1939   ** value.
  1950   1940   ** 
  1951   1941   */
  1952   1942   static WhereCost whereCostAdd(WhereCost a, WhereCost b){
  1953   1943     static const unsigned char x[] = {
  1954   1944        10, 10,                         /* 0,1 */
................................................................................
  2231   2221     sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  2232   2222                       (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  2233   2223     VdbeComment((v, "for %s", pTable->zName));
  2234   2224   
  2235   2225     /* Fill the automatic index with content */
  2236   2226     addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  2237   2227     regRecord = sqlite3GetTempReg(pParse);
  2238         -  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
         2228  +  sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
  2239   2229     sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  2240   2230     sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  2241   2231     sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  2242   2232     sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  2243   2233     sqlite3VdbeJumpHere(v, addrTop);
  2244   2234     sqlite3ReleaseTempReg(pParse, regRecord);
  2245   2235     
................................................................................
  2588   2578     sqlite3_value **pp
  2589   2579   ){
  2590   2580     if( pExpr->op==TK_VARIABLE
  2591   2581      || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  2592   2582     ){
  2593   2583       int iVar = pExpr->iColumn;
  2594   2584       sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  2595         -    *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
         2585  +    *pp = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, aff);
  2596   2586       return SQLITE_OK;
  2597   2587     }
  2598   2588     return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
  2599   2589   }
  2600   2590   #endif
  2601   2591   
  2602   2592   /*
................................................................................
  2814   2804   **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  2815   2805   **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  2816   2806   **
  2817   2807   ** The t2.z='ok' is disabled in the in (2) because it originates
  2818   2808   ** in the ON clause.  The term is disabled in (3) because it is not part
  2819   2809   ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
  2820   2810   **
  2821         -** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
  2822         -** completely satisfied by indices.
  2823         -**
  2824   2811   ** Disabling a term causes that term to not be tested in the inner loop
  2825   2812   ** of the join.  Disabling is an optimization.  When terms are satisfied
  2826   2813   ** by indices, we disable them to prevent redundant tests in the inner
  2827   2814   ** loop.  We would get the correct results if nothing were ever disabled,
  2828   2815   ** but joins might run a little slower.  The trick is to disable as much
  2829   2816   ** as we can without disabling too much.  If we disabled in (1), we'd get
  2830   2817   ** the wrong answer.  See ticket #813.
................................................................................
  3046   3033     for(j=0; j<nEq; j++){
  3047   3034       int r1;
  3048   3035       pTerm = pLoop->aLTerm[j];
  3049   3036       assert( pTerm!=0 );
  3050   3037       /* The following true for indices with redundant columns. 
  3051   3038       ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  3052   3039       testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  3053         -    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
         3040  +    testcase( pTerm->wtFlags & TERM_VIRTUAL );
  3054   3041       r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  3055   3042       if( r1!=regBase+j ){
  3056   3043         if( nReg==1 ){
  3057   3044           sqlite3ReleaseTempReg(pParse, regBase);
  3058   3045           regBase = r1;
  3059   3046         }else{
  3060   3047           sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
................................................................................
  3246   3233     int omitTable;       /* True if we use the index only */
  3247   3234     int bRev;            /* True if we need to scan in reverse order */
  3248   3235     WhereLevel *pLevel;  /* The where level to be coded */
  3249   3236     WhereLoop *pLoop;    /* The WhereLoop object being coded */
  3250   3237     WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
  3251   3238     WhereTerm *pTerm;               /* A WHERE clause term */
  3252   3239     Parse *pParse;                  /* Parsing context */
         3240  +  sqlite3 *db;                    /* Database connection */
  3253   3241     Vdbe *v;                        /* The prepared stmt under constructions */
  3254   3242     struct SrcList_item *pTabItem;  /* FROM clause term being coded */
  3255   3243     int addrBrk;                    /* Jump here to break out of the loop */
  3256   3244     int addrCont;                   /* Jump here to continue with next cycle */
  3257   3245     int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
  3258   3246     int iReleaseReg = 0;      /* Temp register to free before returning */
  3259   3247     Bitmask newNotReady;      /* Return value */
  3260   3248   
  3261   3249     pParse = pWInfo->pParse;
  3262   3250     v = pParse->pVdbe;
  3263   3251     pWC = &pWInfo->sWC;
         3252  +  db = pParse->db;
  3264   3253     pLevel = &pWInfo->a[iLevel];
  3265   3254     pLoop = pLevel->pWLoop;
  3266   3255     pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  3267   3256     iCur = pTabItem->iCursor;
  3268   3257     bRev = (pWInfo->revMask>>iLevel)&1;
  3269   3258     omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 
  3270   3259              && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
................................................................................
  3355   3344       */
  3356   3345       assert( pLoop->u.btree.nEq==1 );
  3357   3346       iReleaseReg = sqlite3GetTempReg(pParse);
  3358   3347       pTerm = pLoop->aLTerm[0];
  3359   3348       assert( pTerm!=0 );
  3360   3349       assert( pTerm->pExpr!=0 );
  3361   3350       assert( omitTable==0 );
  3362         -    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
         3351  +    testcase( pTerm->wtFlags & TERM_VIRTUAL );
  3363   3352       iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  3364   3353       addrNxt = pLevel->addrNxt;
  3365   3354       sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  3366   3355       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  3367   3356       sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  3368   3357       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  3369   3358       VdbeComment((v, "pk"));
................................................................................
  3403   3392              /* TK_GE */  OP_SeekGe
  3404   3393         };
  3405   3394         assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
  3406   3395         assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
  3407   3396         assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
  3408   3397   
  3409   3398         assert( (pStart->wtFlags & TERM_VNULL)==0 );
  3410         -      testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
         3399  +      testcase( pStart->wtFlags & TERM_VIRTUAL );
  3411   3400         pX = pStart->pExpr;
  3412   3401         assert( pX!=0 );
  3413   3402         testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  3414   3403         r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  3415   3404         sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  3416   3405         VdbeComment((v, "pk"));
  3417   3406         sqlite3ExprCacheAffinityChange(pParse, r1, 1);
................................................................................
  3422   3411       }
  3423   3412       if( pEnd ){
  3424   3413         Expr *pX;
  3425   3414         pX = pEnd->pExpr;
  3426   3415         assert( pX!=0 );
  3427   3416         assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  3428   3417         testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  3429         -      testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
         3418  +      testcase( pEnd->wtFlags & TERM_VIRTUAL );
  3430   3419         memEndValue = ++pParse->nMem;
  3431   3420         sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  3432   3421         if( pX->op==TK_LT || pX->op==TK_GT ){
  3433   3422           testOp = bRev ? OP_Le : OP_Ge;
  3434   3423         }else{
  3435   3424           testOp = bRev ? OP_Lt : OP_Gt;
  3436   3425         }
................................................................................
  3547   3536       }
  3548   3537   
  3549   3538       /* Generate code to evaluate all constraint terms using == or IN
  3550   3539       ** and store the values of those terms in an array of registers
  3551   3540       ** starting at regBase.
  3552   3541       */
  3553   3542       regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  3554         -    zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
         3543  +    zEndAff = sqlite3DbStrDup(db, zStartAff);
  3555   3544       addrNxt = pLevel->addrNxt;
  3556   3545   
  3557   3546       /* If we are doing a reverse order scan on an ascending index, or
  3558   3547       ** a forward order scan on a descending index, interchange the 
  3559   3548       ** start and end terms (pRangeStart and pRangeEnd).
  3560   3549       */
  3561   3550       if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
................................................................................
  3588   3577             zStartAff[nEq] = SQLITE_AFF_NONE;
  3589   3578           }
  3590   3579           if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  3591   3580             zStartAff[nEq] = SQLITE_AFF_NONE;
  3592   3581           }
  3593   3582         }  
  3594   3583         nConstraint++;
  3595         -      testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
         3584  +      testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  3596   3585       }else if( isMinQuery ){
  3597   3586         sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  3598   3587         nConstraint++;
  3599   3588         startEq = 0;
  3600   3589         start_constraints = 1;
  3601   3590       }
  3602   3591       codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
................................................................................
  3630   3619           }
  3631   3620           if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  3632   3621             zEndAff[nEq] = SQLITE_AFF_NONE;
  3633   3622           }
  3634   3623         }  
  3635   3624         codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  3636   3625         nConstraint++;
  3637         -      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
         3626  +      testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  3638   3627       }
  3639         -    sqlite3DbFree(pParse->db, zStartAff);
  3640         -    sqlite3DbFree(pParse->db, zEndAff);
         3628  +    sqlite3DbFree(db, zStartAff);
         3629  +    sqlite3DbFree(db, zEndAff);
  3641   3630   
  3642   3631       /* Top of the loop body */
  3643   3632       pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  3644   3633   
  3645   3634       /* Check if the index cursor is past the end of the range. */
  3646   3635       op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  3647   3636       testcase( op==OP_Noop );
................................................................................
  3760   3749       ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  3761   3750       ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  3762   3751       */
  3763   3752       if( pWInfo->nLevel>1 ){
  3764   3753         int nNotReady;                 /* The number of notReady tables */
  3765   3754         struct SrcList_item *origSrc;     /* Original list of tables */
  3766   3755         nNotReady = pWInfo->nLevel - iLevel - 1;
  3767         -      pOrTab = sqlite3StackAllocRaw(pParse->db,
         3756  +      pOrTab = sqlite3StackAllocRaw(db,
  3768   3757                               sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  3769   3758         if( pOrTab==0 ) return notReady;
  3770   3759         pOrTab->nAlloc = (u8)(nNotReady + 1);
  3771   3760         pOrTab->nSrc = pOrTab->nAlloc;
  3772   3761         memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  3773   3762         origSrc = pWInfo->pTabList->a;
  3774   3763         for(k=1; k<=nNotReady; k++){
................................................................................
  3814   3803         int iTerm;
  3815   3804         for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  3816   3805           Expr *pExpr = pWC->a[iTerm].pExpr;
  3817   3806           if( &pWC->a[iTerm] == pTerm ) continue;
  3818   3807           if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  3819   3808           if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
  3820   3809           if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  3821         -        pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  3822         -        pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
         3810  +        pExpr = sqlite3ExprDup(db, pExpr, 0);
         3811  +        pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  3823   3812         }
  3824   3813         if( pAndExpr ){
  3825   3814           pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  3826   3815         }
  3827   3816       }
  3828   3817   
  3829   3818       for(ii=0; ii<pOrWc->nTerm; ii++){
................................................................................
  3835   3824             pAndExpr->pLeft = pOrExpr;
  3836   3825             pOrExpr = pAndExpr;
  3837   3826           }
  3838   3827           /* Loop through table entries that match term pOrTerm. */
  3839   3828           pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  3840   3829                           WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  3841   3830                           WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  3842         -        assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
         3831  +        assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  3843   3832           if( pSubWInfo ){
  3844   3833             WhereLoop *pSubLoop;
  3845   3834             explainOneScan(
  3846   3835                 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  3847   3836             );
  3848   3837             if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  3849   3838               int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
................................................................................
  3890   3879           }
  3891   3880         }
  3892   3881       }
  3893   3882       pLevel->u.pCovidx = pCov;
  3894   3883       if( pCov ) pLevel->iIdxCur = iCovCur;
  3895   3884       if( pAndExpr ){
  3896   3885         pAndExpr->pLeft = 0;
  3897         -      sqlite3ExprDelete(pParse->db, pAndExpr);
         3886  +      sqlite3ExprDelete(db, pAndExpr);
  3898   3887       }
  3899   3888       sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  3900   3889       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  3901   3890       sqlite3VdbeResolveLabel(v, iLoopBody);
  3902   3891   
  3903         -    if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
         3892  +    if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  3904   3893       if( !untestedTerms ) disableTerm(pLevel, pTerm);
  3905   3894     }else
  3906   3895   #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  3907   3896   
  3908   3897     {
  3909   3898       /* Case 6:  There is no usable index.  We must do a complete
  3910   3899       **          scan of the entire table.
................................................................................
  3917   3906       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  3918   3907       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  3919   3908     }
  3920   3909     newNotReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  3921   3910   
  3922   3911     /* Insert code to test every subexpression that can be completely
  3923   3912     ** computed using the current set of tables.
  3924         -  **
  3925         -  ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
  3926         -  ** the use of indices become tests that are evaluated against each row of
  3927         -  ** the relevant input tables.
  3928   3913     */
  3929   3914     for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  3930   3915       Expr *pE;
  3931         -    testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
         3916  +    testcase( pTerm->wtFlags & TERM_VIRTUAL );
  3932   3917       testcase( pTerm->wtFlags & TERM_CODED );
  3933   3918       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  3934   3919       if( (pTerm->prereqAll & newNotReady)!=0 ){
  3935   3920         testcase( pWInfo->untestedTerms==0
  3936   3921                  && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  3937   3922         pWInfo->untestedTerms = 1;
  3938   3923         continue;
................................................................................
  3951   3936     **
  3952   3937     ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  3953   3938     ** and we are coding the t1 loop and the t2 loop has not yet coded,
  3954   3939     ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  3955   3940     ** the implied "t1.a=123" constraint.
  3956   3941     */
  3957   3942     for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  3958         -    Expr *pE;
         3943  +    Expr *pE, *pEAlt;
  3959   3944       WhereTerm *pAlt;
  3960         -    Expr sEq;
  3961   3945       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  3962   3946       if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  3963   3947       if( pTerm->leftCursor!=iCur ) continue;
  3964   3948       if( pLevel->iLeftJoin ) continue;
  3965   3949       pE = pTerm->pExpr;
  3966   3950       assert( !ExprHasProperty(pE, EP_FromJoin) );
  3967   3951       assert( (pTerm->prereqRight & newNotReady)!=0 );
  3968   3952       pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  3969   3953       if( pAlt==0 ) continue;
  3970   3954       if( pAlt->wtFlags & (TERM_CODED) ) continue;
  3971   3955       testcase( pAlt->eOperator & WO_EQ );
  3972   3956       testcase( pAlt->eOperator & WO_IN );
  3973   3957       VdbeNoopComment((v, "begin transitive constraint"));
  3974         -    sEq = *pAlt->pExpr;
  3975         -    sEq.pLeft = pE->pLeft;
  3976         -    sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
         3958  +    pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
         3959  +    if( pEAlt ){
         3960  +      *pEAlt = *pAlt->pExpr;
         3961  +      pEAlt->pLeft = pE->pLeft;
         3962  +      sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
         3963  +      sqlite3StackFree(db, pEAlt);
         3964  +    }
  3977   3965     }
  3978   3966   
  3979   3967     /* For a LEFT OUTER JOIN, generate code that will record the fact that
  3980   3968     ** at least one row of the right table has matched the left table.  
  3981   3969     */
  3982   3970     if( pLevel->iLeftJoin ){
  3983   3971       pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  3984   3972       sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  3985   3973       VdbeComment((v, "record LEFT JOIN hit"));
  3986   3974       sqlite3ExprCacheClear(pParse);
  3987   3975       for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  3988         -      testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
         3976  +      testcase( pTerm->wtFlags & TERM_VIRTUAL );
  3989   3977         testcase( pTerm->wtFlags & TERM_CODED );
  3990   3978         if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  3991   3979         if( (pTerm->prereqAll & newNotReady)!=0 ){
  3992   3980           assert( pWInfo->untestedTerms );
  3993   3981           continue;
  3994   3982         }
  3995   3983         assert( pTerm->pExpr );
................................................................................
  4422   4410           testcase( pTerm->eOperator & WO_EQ );
  4423   4411           testcase( pTerm->eOperator & WO_ISNULL );
  4424   4412           rc = whereEqualScanEst(pParse, pProbe, pTerm->pExpr->pRight, &nOut);
  4425   4413         }else if( (pTerm->eOperator & WO_IN)
  4426   4414                &&  !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)  ){
  4427   4415           rc = whereInScanEst(pParse, pProbe, pTerm->pExpr->x.pList, &nOut);
  4428   4416         }
  4429         -      if( rc==SQLITE_OK ) pNew->nOut = whereCost(nOut);
         4417  +      assert( nOut==0 || rc==SQLITE_OK );
         4418  +      if( nOut ) pNew->nOut = whereCost(nOut);
  4430   4419       }
  4431   4420   #endif
  4432   4421       if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  4433   4422         /* Each row involves a step of the index, then a binary search of
  4434   4423         ** the main table */
  4435   4424         pNew->rRun =  whereCostAdd(pNew->rRun, rLogSize>27 ? rLogSize-17 : 10);
  4436   4425       }
................................................................................
  4494   4483       testcase( x==BMS-1 );
  4495   4484       testcase( x==BMS-2 );
  4496   4485       if( x<BMS-1 ) m |= MASKBIT(x);
  4497   4486     }
  4498   4487     return m;
  4499   4488   }
  4500   4489   
         4490  +/* Check to see if a partial index with pPartIndexWhere can be used
         4491  +** in the current query.  Return true if it can be and false if not.
         4492  +*/
         4493  +static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
         4494  +  int i;
         4495  +  WhereTerm *pTerm;
         4496  +  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
         4497  +    if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
         4498  +  }
         4499  +  return 0;
         4500  +}
  4501   4501   
  4502   4502   /*
  4503   4503   ** Add all WhereLoop objects for a single table of the join where the table
  4504   4504   ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
  4505   4505   ** a b-tree table, not a virtual table.
  4506   4506   */
  4507   4507   static int whereLoopAddBtree(
................................................................................
  4517   4517     struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
  4518   4518     WhereLoop *pNew;            /* Template WhereLoop object */
  4519   4519     int rc = SQLITE_OK;         /* Return code */
  4520   4520     int iSortIdx = 1;           /* Index number */
  4521   4521     int b;                      /* A boolean value */
  4522   4522     WhereCost rSize;            /* number of rows in the table */
  4523   4523     WhereCost rLogSize;         /* Logarithm of the number of rows in the table */
         4524  +  WhereClause *pWC;           /* The parsed WHERE clause */
  4524   4525     
  4525   4526     pNew = pBuilder->pNew;
  4526   4527     pWInfo = pBuilder->pWInfo;
  4527   4528     pTabList = pWInfo->pTabList;
  4528   4529     pSrc = pTabList->a + pNew->iTab;
         4530  +  pWC = pBuilder->pWC;
  4529   4531     assert( !IsVirtual(pSrc->pTab) );
  4530   4532   
  4531   4533     if( pSrc->pIndex ){
  4532   4534       /* An INDEXED BY clause specifies a particular index to use */
  4533   4535       pProbe = pSrc->pIndex;
  4534   4536     }else{
  4535   4537       /* There is no INDEXED BY clause.  Create a fake Index object in local
................................................................................
  4561   4563      && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  4562   4564      && pSrc->pIndex==0
  4563   4565      && !pSrc->viaCoroutine
  4564   4566      && !pSrc->notIndexed
  4565   4567      && !pSrc->isCorrelated
  4566   4568     ){
  4567   4569       /* Generate auto-index WhereLoops */
  4568         -    WhereClause *pWC = pBuilder->pWC;
  4569   4570       WhereTerm *pTerm;
  4570   4571       WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  4571   4572       for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  4572   4573         if( pTerm->prereqRight & pNew->maskSelf ) continue;
  4573   4574         if( termCanDriveIndex(pTerm, pSrc, 0) ){
  4574   4575           pNew->u.btree.nEq = 1;
  4575   4576           pNew->u.btree.pIndex = 0;
................................................................................
  4591   4592         }
  4592   4593       }
  4593   4594     }
  4594   4595   
  4595   4596     /* Loop over all indices
  4596   4597     */
  4597   4598     for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
         4599  +    if( pProbe->pPartIdxWhere!=0
         4600  +     && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
         4601  +      continue;  /* Partial index inappropriate for this query */
         4602  +    }
  4598   4603       pNew->u.btree.nEq = 0;
  4599   4604       pNew->nLTerm = 0;
  4600   4605       pNew->iSortIdx = 0;
  4601   4606       pNew->rSetup = 0;
  4602   4607       pNew->prereq = mExtra;
  4603   4608       pNew->nOut = rSize;
  4604   4609       pNew->u.btree.pIndex = pProbe;
................................................................................
  5531   5536       pLoop->aLTerm[0] = pTerm;
  5532   5537       pLoop->nLTerm = 1;
  5533   5538       pLoop->u.btree.nEq = 1;
  5534   5539       /* TUNING: Cost of a rowid lookup is 10 */
  5535   5540       pLoop->rRun = 33;  /* 33==whereCost(10) */
  5536   5541     }else{
  5537   5542       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  5538         -      if( pIdx->onError==OE_None ) continue;
         5543  +      if( pIdx->onError==OE_None || pIdx->pPartIdxWhere!=0 ) continue;
  5539   5544         for(j=0; j<pIdx->nColumn; j++){
  5540   5545           pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  5541   5546           if( pTerm==0 ) break;
  5542   5547           whereLoopResize(pWInfo->pParse->db, pLoop, j);
  5543   5548           pLoop->aLTerm[j] = pTerm;
  5544   5549         }
  5545   5550         if( j!=pIdx->nColumn ) continue;
................................................................................
  5737   5742   
  5738   5743     /* Split the WHERE clause into separate subexpressions where each
  5739   5744     ** subexpression is separated by an AND operator.
  5740   5745     */
  5741   5746     initMaskSet(pMaskSet);
  5742   5747     whereClauseInit(&pWInfo->sWC, pWInfo);
  5743   5748     sqlite3ExprCodeConstants(pParse, pWhere);
  5744         -  whereSplit(&pWInfo->sWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
         5749  +  whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  5745   5750     sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  5746   5751       
  5747   5752     /* Special case: a WHERE clause that is constant.  Evaluate the
  5748   5753     ** expression and either jump over all of the code or fall thru.
  5749   5754     */
  5750   5755     if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  5751   5756       sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);

Changes to test/analyze3.test.

    39     39   #
    40     40   # analyze3-4.*: Test that SQL or authorization callback errors occuring
    41     41   #               within sqlite3Reprepare() are handled correctly.
    42     42   #
    43     43   # analyze3-5.*: Check that the query plans of applicable statements are
    44     44   #               invalidated if the values of SQL parameter are modified
    45     45   #               using the clear_bindings() or transfer_bindings() APIs.
           46  +# 
           47  +# analyze3-6.*: Test that the problem fixed by commit [127a5b776d] is fixed.
    46     48   #
    47     49   
    48     50   proc getvar {varname} { uplevel #0 set $varname }
    49     51   db function var getvar
    50     52   
    51     53   proc eqp {sql {db db}} {
    52     54     uplevel execsql [list "EXPLAIN QUERY PLAN $sql"] $db
................................................................................
   607    609     }
   608    610     concat [sqlite3_reset $S1] $R
   609    611   } {SQLITE_OK aaa abb acc}
   610    612   do_test analyze3-5.1.3 {
   611    613     sqlite3_finalize $S2
   612    614     sqlite3_finalize $S1
   613    615   } {SQLITE_OK}
          616  +
          617  +#-------------------------------------------------------------------------
          618  +
          619  +do_test analyze3-6.1 {
          620  +  execsql { DROP TABLE IF EXISTS t1 }
          621  +  execsql BEGIN
          622  +  execsql { CREATE TABLE t1(a, b, c) }
          623  +  for {set i 0} {$i < 1000} {incr i} {
          624  +    execsql "INSERT INTO t1 VALUES([expr $i/100], 'x', [expr $i/10])"
          625  +  }
          626  +  execsql {
          627  +    CREATE INDEX i1 ON t1(a, b);
          628  +    CREATE INDEX i2 ON t1(c);
          629  +  }
          630  +  execsql COMMIT
          631  +  execsql ANALYZE
          632  +} {}
          633  +
          634  +do_eqp_test analyze3-6-3 {
          635  +  SELECT * FROM t1 WHERE a = 5 AND c = 13;
          636  +} {0 0 0 {SEARCH TABLE t1 USING INDEX i2 (c=?)}}
          637  +
          638  +do_eqp_test analyze3-6-2 {
          639  +  SELECT * FROM t1 WHERE a = 5 AND b > 'w' AND c = 13;
          640  +} {0 0 0 {SEARCH TABLE t1 USING INDEX i2 (c=?)}}
   614    641   
   615    642   finish_test

Changes to test/check.test.

   447    447   } {}
   448    448   
   449    449   do_test 7.8 {
   450    450     db2 func myfunc myfunc
   451    451     catchsql { INSERT INTO t6 VALUES(12) } db2
   452    452   } {1 {constraint failed}}
   453    453   
          454  +# 2013-08-02:  Silently ignore database name qualifiers in CHECK constraints.
          455  +#
          456  +do_execsql_test 8.1 {
          457  +  CREATE TABLE t810(a, CHECK( main.t810.a>0 ));
          458  +  CREATE TABLE t811(b, CHECK( xyzzy.t811.b BETWEEN 5 AND 10 ));
          459  +} {}
   454    460   
   455    461   finish_test

Added test/corruptG.test.

            1  +# 2013-08-01
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +#
           12  +
           13  +set testdir [file dirname $argv0]
           14  +source $testdir/tester.tcl
           15  +set testprefix corruptG
           16  +
           17  +# Do not use a codec for tests in this file, as the database file is
           18  +# manipulated directly using tcl scripts (using the [hexio_write] command).
           19  +#
           20  +do_not_use_codec
           21  +
           22  +# Create a simple database with a single entry.  Then corrupt the
           23  +# header-size varint on the index payload so that it maps into a
           24  +# negative number.  Try to use the database.
           25  +#
           26  +
           27  +do_execsql_test 1.1 {
           28  +  PRAGMA page_size=512;
           29  +  CREATE TABLE t1(a,b,c);
           30  +  INSERT INTO t1(rowid,a,b,c) VALUES(52,'abc','xyz','123');
           31  +  CREATE INDEX t1abc ON t1(a,b,c);
           32  +}
           33  +
           34  +# Corrupt the file
           35  +db close
           36  +hexio_write test.db [expr {3*512 - 15}] 888080807f
           37  +sqlite3 db test.db
           38  +
           39  +# Try to use the file.
           40  +do_test 1.2 {
           41  +  catchsql {
           42  +    SELECT c FROM t1 WHERE a>'abc';
           43  +  }
           44  +} {0 {}}
           45  +do_test 1.3 {
           46  +  catchsql {
           47  +     PRAGMA integrity_check
           48  +  }
           49  +} {0 ok}
           50  +do_test 1.4 {
           51  +  catchsql {
           52  +    SELECT c FROM t1 ORDER BY a;
           53  +  }
           54  +} {1 {database disk image is malformed}}
           55  +
           56  +# Corrupt the same file in a slightly different way.  Make the record header
           57  +# sane, but corrupt one of the serial_type value to indicate a huge payload
           58  +# such that the payload begins in allocated space but overflows the buffer.
           59  +#
           60  +db close
           61  +hexio_write test.db [expr {3*512-15}] 0513ff7f01
           62  +sqlite3 db test.db
           63  +
           64  +do_test 2.1 {
           65  +  catchsql {
           66  +    SELECT rowid FROM t1 WHERE a='abc' and b='xyz123456789XYZ';
           67  +  }
           68  +  # The following test result is brittle.  The point above is to try to
           69  +  # force a buffer overread by a corrupt database file.  If we get an
           70  +  # incorrect answer from a corrupt database file, that is OK.  If the
           71  +  # result below changes, that just means that "undefined behavior" has
           72  +  # changed.
           73  +} {0 52}
           74  +
           75  +finish_test

Changes to test/e_createtable.test.

    54     54         db eval "SELECT DISTINCT tbl_name FROM $master ORDER BY tbl_name"
    55     55       ]
    56     56     }
    57     57     set res
    58     58   }
    59     59   
    60     60   
    61         -# EVIDENCE-OF: R-47266-09114 -- syntax diagram type-name
    62         -#
    63     61   do_createtable_tests 0.1.1 -repair {
    64     62     drop_all_tables
    65     63   } {
    66     64     1   "CREATE TABLE t1(c1 one)"                        {}
    67     65     2   "CREATE TABLE t1(c1 one two)"                    {}
    68     66     3   "CREATE TABLE t1(c1 one two three)"              {}
    69     67     4   "CREATE TABLE t1(c1 one two three four)"         {}
................................................................................
    75     73   do_createtable_tests 0.1.2 -error {
    76     74     near "%s": syntax error
    77     75   } {
    78     76     1   "CREATE TABLE t1(c1 one(number))"                {number}
    79     77   }
    80     78   
    81     79   
    82         -# EVIDENCE-OF: R-60689-48779 -- syntax diagram column-constraint
           80  +# syntax diagram column-constraint
    83     81   #
    84     82   do_createtable_tests 0.2.1 -repair {
    85     83     drop_all_tables 
    86     84     execsql { CREATE TABLE t2(x PRIMARY KEY) }
    87     85   } {
    88     86     1.1   "CREATE TABLE t1(c1 text PRIMARY KEY)"                         {}
    89     87     1.2   "CREATE TABLE t1(c1 text PRIMARY KEY ASC)"                     {}
................................................................................
   122    120     8.2   {
   123    121       CREATE TABLE t1(c1 
   124    122         REFERENCES t1 DEFAULT 123 CHECK(c1 IS 'ten') UNIQUE NOT NULL PRIMARY KEY 
   125    123       );
   126    124     } {}
   127    125   }
   128    126   
   129         -# EVIDENCE-OF: R-58169-51804 -- syntax diagram table-constraint
          127  +# -- syntax diagram table-constraint
   130    128   #
   131    129   do_createtable_tests 0.3.1 -repair {
   132    130     drop_all_tables 
   133    131     execsql { CREATE TABLE t2(x PRIMARY KEY) }
   134    132   } {
   135    133     1.1   "CREATE TABLE t1(c1, c2, PRIMARY KEY(c1))"                         {}
   136    134     1.2   "CREATE TABLE t1(c1, c2, PRIMARY KEY(c1, c2))"                     {}
................................................................................
   141    139     2.3   "CREATE TABLE t1(c1, c2, UNIQUE(c1, c2) ON CONFLICT IGNORE)"       {}
   142    140   
   143    141     3.1   "CREATE TABLE t1(c1, c2, CHECK(c1 IS NOT c2))"                     {}
   144    142   
   145    143     4.1   "CREATE TABLE t1(c1, c2, FOREIGN KEY(c1) REFERENCES t2)"           {}
   146    144   }
   147    145   
   148         -# EVIDENCE-OF: R-44826-22243 -- syntax diagram column-def
          146  +# -- syntax diagram column-def
   149    147   #
   150    148   do_createtable_tests 0.4.1 -repair {
   151    149     drop_all_tables 
   152    150   } {
   153    151     1     {CREATE TABLE t1(
   154    152              col1,
   155    153              col2 TEXT,
................................................................................
   156    154              col3 INTEGER UNIQUE,
   157    155              col4 VARCHAR(10, 10) PRIMARY KEY,
   158    156              "name with spaces" REFERENCES t1
   159    157            );
   160    158           } {}
   161    159   }
   162    160   
   163         -# EVIDENCE-OF: R-45698-45677 -- syntax diagram create-table-stmt
          161  +# -- syntax diagram create-table-stmt
   164    162   #
   165    163   do_createtable_tests 0.5.1 -repair {
   166    164     drop_all_tables 
   167    165     execsql { CREATE TABLE t2(a, b, c) }
   168    166   } {
   169    167     1     "CREATE TABLE t1(a, b, c)"                                    {}
   170    168     2     "CREATE TEMP TABLE t1(a, b, c)"                               {}
................................................................................
   181    179     12    "CREATE TEMPORARY TABLE IF NOT EXISTS temp.t1(a, b, c)"       {}
   182    180   
   183    181     13    "CREATE TABLE t1 AS SELECT * FROM t2"                         {}
   184    182     14    "CREATE TEMP TABLE t1 AS SELECT c, b, a FROM t2"              {}
   185    183     15    "CREATE TABLE t1 AS SELECT count(*), max(b), min(a) FROM t2"  {}
   186    184   }
   187    185   
   188         -# EVIDENCE-OF: R-24369-11919 -- syntax diagram foreign-key-clause
   189    186   #
   190    187   #   1:         Explicit parent-key columns.
   191    188   #   2:         Implicit child-key columns.
   192    189   #
   193    190   #   1:         MATCH FULL
   194    191   #   2:         MATCH PARTIAL
   195    192   #   3:         MATCH SIMPLE

Changes to test/e_delete.test.

    25     25   }
    26     26   
    27     27   do_execsql_test e_delete-0.0 {
    28     28     CREATE TABLE t1(a, b);
    29     29     CREATE INDEX i1 ON t1(a);
    30     30   } {}
    31     31   
    32         -# EVIDENCE-OF: R-62077-19799 -- syntax diagram delete-stmt
    33         -#
    34         -# EVIDENCE-OF: R-60796-31013 -- syntax diagram qualified-table-name
           32  +# -- syntax diagram delete-stmt
           33  +# -- syntax diagram qualified-table-name
    35     34   #
    36     35   do_delete_tests e_delete-0.1 {
    37     36     1  "DELETE FROM t1"                              {}
    38     37     2  "DELETE FROM t1 INDEXED BY i1"                {}
    39     38     3  "DELETE FROM t1 NOT INDEXED"                  {}
    40     39     4  "DELETE FROM main.t1"                         {}
    41     40     5  "DELETE FROM main.t1 INDEXED BY i1"           {}
................................................................................
   288    287   }
   289    288   
   290    289   # EVIDENCE-OF: R-40026-10531 If SQLite is compiled with the
   291    290   # SQLITE_ENABLE_UPDATE_DELETE_LIMIT compile-time option, then the syntax
   292    291   # of the DELETE statement is extended by the addition of optional ORDER
   293    292   # BY and LIMIT clauses:
   294    293   #
   295         -# EVIDENCE-OF: R-52694-53361 -- syntax diagram delete-stmt-limited
          294  +# -- syntax diagram delete-stmt-limited
   296    295   #
   297    296   do_delete_tests e_delete-3.1 {
   298    297     1   "DELETE FROM t1 LIMIT 5"                                    {}
   299    298     2   "DELETE FROM t1 LIMIT 5-1 OFFSET 2+2"                       {}
   300    299     3   "DELETE FROM t1 LIMIT 2+2, 16/4"                            {}
   301    300     4   "DELETE FROM t1 ORDER BY x LIMIT 5"                         {}
   302    301     5   "DELETE FROM t1 ORDER BY x LIMIT 5-1 OFFSET 2+2"            {}

Changes to test/e_droptrigger.test.

    65     65       CREATE TRIGGER aux.tr1 BEFORE $event ON t3 BEGIN SELECT r('aux.tr1') ; END;
    66     66       CREATE TRIGGER aux.tr2 AFTER  $event ON t3 BEGIN SELECT r('aux.tr2') ; END;
    67     67       CREATE TRIGGER aux.tr3 AFTER  $event ON t3 BEGIN SELECT r('aux.tr3') ; END;
    68     68     "
    69     69   }
    70     70   
    71     71   
    72         -# EVIDENCE-OF: R-27975-10951 -- syntax diagram drop-trigger-stmt
           72  +# -- syntax diagram drop-trigger-stmt
    73     73   #
    74     74   do_droptrigger_tests 1.1 -repair {
    75     75     droptrigger_reopen_db
    76     76   } -tclquery {
    77     77     list_all_triggers 
    78     78   } {
    79     79     1   "DROP TRIGGER main.tr1"            

Changes to test/e_dropview.test.

    66     66     set res
    67     67   }
    68     68   
    69     69   proc do_dropview_tests {nm args} {
    70     70     uplevel do_select_tests $nm $args
    71     71   }
    72     72   
    73         -# EVIDENCE-OF: R-53136-36436 -- syntax diagram drop-view-stmt
           73  +# -- syntax diagram drop-view-stmt
    74     74   #
    75     75   # All paths in the syntax diagram for DROP VIEW are tested by tests 1.*.
    76     76   #
    77     77   do_dropview_tests 1 -repair {
    78     78     dropview_reopen_db
    79     79   } -tclquery {
    80     80     list_all_views

Changes to test/e_expr.test.

   362    362     string compare [reverse_str $zLeft] [reverse_str $zRight]
   363    363   }
   364    364   db collate reverse reverse_collate
   365    365   
   366    366   # EVIDENCE-OF: R-59577-33471 The COLLATE operator is a unary postfix
   367    367   # operator that assigns a collating sequence to an expression.
   368    368   #
   369         -# EVIDENCE-OF: R-23441-22541 The COLLATE operator has a higher
   370         -# precedence (binds more tightly) than any prefix unary operator or any
   371         -# binary operator.
          369  +# EVIDENCE-OF: R-36231-30731 The COLLATE operator has a higher
          370  +# precedence (binds more tightly) than any binary operator and any unary
          371  +# prefix operator except "~".
   372    372   #
   373    373   do_execsql_test e_expr-9.1 { SELECT  'abcd' < 'bbbb'    COLLATE reverse } 0
   374    374   do_execsql_test e_expr-9.2 { SELECT ('abcd' < 'bbbb')   COLLATE reverse } 1
   375    375   do_execsql_test e_expr-9.3 { SELECT  'abcd' <= 'bbbb'   COLLATE reverse } 0
   376    376   do_execsql_test e_expr-9.4 { SELECT ('abcd' <= 'bbbb')  COLLATE reverse } 1
   377    377   
   378    378   do_execsql_test e_expr-9.5 { SELECT  'abcd' > 'bbbb'    COLLATE reverse } 1
................................................................................
   627    627          [sqlite3_column_type $stmt 3] 
   628    628   } {NULL NULL NULL NULL}
   629    629   do_test e_expr-11.7.1 { sqlite3_finalize $stmt } SQLITE_OK
   630    630   
   631    631   #-------------------------------------------------------------------------
   632    632   # "Test" the syntax diagrams in lang_expr.html.
   633    633   #
   634         -# EVIDENCE-OF: R-02989-21050 -- syntax diagram signed-number
          634  +# -- syntax diagram signed-number
   635    635   #
   636    636   do_execsql_test e_expr-12.1.1 { SELECT 0, +0, -0 } {0 0 0}
   637    637   do_execsql_test e_expr-12.1.2 { SELECT 1, +1, -1 } {1 1 -1}
   638    638   do_execsql_test e_expr-12.1.3 { SELECT 2, +2, -2 } {2 2 -2}
   639    639   do_execsql_test e_expr-12.1.4 { 
   640    640     SELECT 1.4, +1.4, -1.4 
   641    641   } {1.4 1.4 -1.4}
................................................................................
   642    642   do_execsql_test e_expr-12.1.5 { 
   643    643     SELECT 1.5e+5, +1.5e+5, -1.5e+5 
   644    644   } {150000.0 150000.0 -150000.0}
   645    645   do_execsql_test e_expr-12.1.6 { 
   646    646     SELECT 0.0001, +0.0001, -0.0001 
   647    647   } {0.0001 0.0001 -0.0001}
   648    648   
   649         -# EVIDENCE-OF: R-43188-60852 -- syntax diagram literal-value
          649  +# -- syntax diagram literal-value
   650    650   #
   651    651   set sqlite_current_time 1
   652    652   do_execsql_test e_expr-12.2.1 {SELECT 123}               {123}
   653    653   do_execsql_test e_expr-12.2.2 {SELECT 123.4e05}          {12340000.0}
   654    654   do_execsql_test e_expr-12.2.3 {SELECT 'abcde'}           {abcde}
   655    655   do_execsql_test e_expr-12.2.4 {SELECT X'414243'}         {ABC}
   656    656   do_execsql_test e_expr-12.2.5 {SELECT NULL}              {{}}
   657    657   do_execsql_test e_expr-12.2.6 {SELECT CURRENT_TIME}      {00:00:01}
   658    658   do_execsql_test e_expr-12.2.7 {SELECT CURRENT_DATE}      {1970-01-01}
   659    659   do_execsql_test e_expr-12.2.8 {SELECT CURRENT_TIMESTAMP} {{1970-01-01 00:00:01}}
   660    660   set sqlite_current_time 0
   661    661   
   662         -# EVIDENCE-OF: R-50544-32159 -- syntax diagram expr
          662  +# -- syntax diagram expr
   663    663   #
   664    664   forcedelete test.db2
   665    665   execsql {
   666    666     ATTACH 'test.db2' AS dbname;
   667    667     CREATE TABLE dbname.tblname(cname);
   668    668   }
   669    669   
................................................................................
   812    812       incr x
   813    813       do_test e_expr-12.3.$tn.$x { 
   814    814         set rc [catch { execsql "SELECT $e FROM tblname" } msg]
   815    815       } {0}
   816    816     }
   817    817   }
   818    818   
   819         -# EVIDENCE-OF: R-39820-63916 -- syntax diagram raise-function
          819  +# -- syntax diagram raise-function
   820    820   #
   821    821   foreach {tn raiseexpr} {
   822    822     1 "RAISE(IGNORE)"
   823    823     2 "RAISE(ROLLBACK, 'error message')"
   824    824     3 "RAISE(ABORT, 'error message')"
   825    825     4 "RAISE(FAIL, 'error message')"
   826    826   } {

Changes to test/e_insert.test.

    46     46     CREATE TABLE a4(c UNIQUE, d);
    47     47   } {}
    48     48   
    49     49   proc do_insert_tests {args} {
    50     50     uplevel do_select_tests $args
    51     51   }
    52     52   
    53         -# EVIDENCE-OF: R-21350-31508 -- syntax diagram insert-stmt
           53  +# -- syntax diagram insert-stmt
    54     54   #
    55     55   do_insert_tests e_insert-0 {
    56     56        1  "INSERT             INTO a1 DEFAULT VALUES"                   {}
    57     57        2  "INSERT             INTO main.a1 DEFAULT VALUES"              {}
    58     58        3  "INSERT OR ROLLBACK INTO main.a1 DEFAULT VALUES"              {}
    59     59        4  "INSERT OR ROLLBACK INTO a1 DEFAULT VALUES"                   {}
    60     60        5  "INSERT OR ABORT    INTO main.a1 DEFAULT VALUES"              {}

Changes to test/e_reindex.test.

    22     22   
    23     23   do_execsql_test e_reindex-0.0 {
    24     24     CREATE TABLE t1(a, b);
    25     25     CREATE INDEX i1 ON t1(a, b);
    26     26     CREATE INDEX i2 ON t1(b, a);
    27     27   } {}
    28     28   
    29         -# EVIDENCE-OF: R-51477-38549 -- syntax diagram reindex-stmt
           29  +#  -- syntax diagram reindex-stmt
    30     30   #
    31     31   do_reindex_tests e_reindex-0.1 {
    32     32     1   "REINDEX"           {}
    33     33     2   "REINDEX nocase"    {}
    34     34     3   "REINDEX binary"    {}
    35     35     4   "REINDEX t1"        {}
    36     36     5   "REINDEX main.t1"   {}

Changes to test/e_select.test.

    79     79     }
    80     80   }
    81     81   
    82     82   #-------------------------------------------------------------------------
    83     83   # The following tests check that all paths on the syntax diagrams on
    84     84   # the lang_select.html page may be taken.
    85     85   #
    86         -# EVIDENCE-OF: R-11353-33501 -- syntax diagram join-constraint
           86  +# -- syntax diagram join-constraint
    87     87   #
    88     88   do_join_test e_select-0.1.1 {
    89     89     SELECT count(*) FROM t1 %JOIN% t2 ON (t1.a=t2.a)
    90     90   } {3}
    91     91   do_join_test e_select-0.1.2 {
    92     92     SELECT count(*) FROM t1 %JOIN% t2 USING (a)
    93     93   } {3}
................................................................................
    97     97   do_catchsql_test e_select-0.1.4 {
    98     98     SELECT count(*) FROM t1, t2 ON (t1.a=t2.a) USING (a)
    99     99   } {1 {cannot have both ON and USING clauses in the same join}}
   100    100   do_catchsql_test e_select-0.1.5 {
   101    101     SELECT count(*) FROM t1, t2 USING (a) ON (t1.a=t2.a)
   102    102   } {1 {near "ON": syntax error}}
   103    103   
   104         -# EVIDENCE-OF: R-40919-40941 -- syntax diagram select-core
          104  +# -- syntax diagram select-core
   105    105   #
   106    106   #   0: SELECT ...
   107    107   #   1: SELECT DISTINCT ...
   108    108   #   2: SELECT ALL ...
   109    109   #
   110    110   #   0: No FROM clause
   111    111   #   1: Has FROM clause
................................................................................
   222    222       1 a 1 c
   223    223     }
   224    224     2112.2  "SELECT ALL count(*), max(a) FROM t1 
   225    225              WHERE 0 GROUP BY b HAVING count(*)=2" { }
   226    226   }
   227    227   
   228    228   
   229         -# EVIDENCE-OF: R-41378-26734 -- syntax diagram result-column
          229  +# -- syntax diagram result-column
   230    230   #
   231    231   do_select_tests e_select-0.3 {
   232    232     1  "SELECT * FROM t1" {a one b two c three}
   233    233     2  "SELECT t1.* FROM t1" {a one b two c three}
   234    234     3  "SELECT 'x'||a||'x' FROM t1" {xax xbx xcx}
   235    235     4  "SELECT 'x'||a||'x' alias FROM t1" {xax xbx xcx}
   236    236     5  "SELECT 'x'||a||'x' AS alias FROM t1" {xax xbx xcx}
   237    237   }
   238    238   
   239         -# EVIDENCE-OF: R-43129-35648 -- syntax diagram join-source
          239  +# -- syntax diagram join-source
   240    240   #
   241         -# EVIDENCE-OF: R-36683-37460 -- syntax diagram join-op
          241  +# -- syntax diagram join-op
   242    242   #
   243    243   do_select_tests e_select-0.4 {
   244    244     1  "SELECT t1.rowid FROM t1" {1 2 3}
   245    245     2  "SELECT t1.rowid FROM t1,t2" {1 1 1 2 2 2 3 3 3}
   246    246     3  "SELECT t1.rowid FROM t1,t2,t3" {1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3}
   247    247   
   248    248     4  "SELECT t1.rowid FROM t1" {1 2 3}
................................................................................
   259    259     12 "SELECT t1.rowid FROM t1 JOIN t3" {1 1 2 2 3 3}
   260    260     13 "SELECT t1.rowid FROM t1 LEFT OUTER JOIN t3" {1 1 2 2 3 3}
   261    261     14 "SELECT t1.rowid FROM t1 LEFT JOIN t3" {1 1 2 2 3 3}
   262    262     15 "SELECT t1.rowid FROM t1 INNER JOIN t3" {1 1 2 2 3 3}
   263    263     16 "SELECT t1.rowid FROM t1 CROSS JOIN t3" {1 1 2 2 3 3}
   264    264   }
   265    265   
   266         -# EVIDENCE-OF: R-28308-37813 -- syntax diagram compound-operator
          266  +# -- syntax diagram compound-operator
   267    267   #
   268    268   do_select_tests e_select-0.5 {
   269    269     1  "SELECT rowid FROM t1 UNION ALL SELECT rowid+2 FROM t4" {1 2 3 3 4}
   270    270     2  "SELECT rowid FROM t1 UNION     SELECT rowid+2 FROM t4" {1 2 3 4}
   271    271     3  "SELECT rowid FROM t1 INTERSECT SELECT rowid+2 FROM t4" {3}
   272    272     4  "SELECT rowid FROM t1 EXCEPT    SELECT rowid+2 FROM t4" {1 2}
   273    273   }
   274    274   
   275         -# EVIDENCE-OF: R-06480-34950 -- syntax diagram ordering-term
          275  +# -- syntax diagram ordering-term
   276    276   #
   277    277   do_select_tests e_select-0.6 {
   278    278     1  "SELECT b||a FROM t1 ORDER BY b||a"                  {onea threec twob}
   279    279     2  "SELECT b||a FROM t1 ORDER BY (b||a) COLLATE nocase" {onea threec twob}
   280    280     3  "SELECT b||a FROM t1 ORDER BY (b||a) ASC"            {onea threec twob}
   281    281     4  "SELECT b||a FROM t1 ORDER BY (b||a) DESC"           {twob threec onea}
   282    282   }
   283    283   
   284         -# EVIDENCE-OF: R-23926-36668 -- syntax diagram select-stmt
          284  +# -- syntax diagram select-stmt
   285    285   #
   286    286   do_select_tests e_select-0.7 {
   287    287     1  "SELECT * FROM t1" {a one b two c three}
   288    288     2  "SELECT * FROM t1 ORDER BY b" {a one c three b two}
   289    289     3  "SELECT * FROM t1 ORDER BY b, a" {a one c three b two}
   290    290   
   291    291     4  "SELECT * FROM t1 LIMIT 10" {a one b two c three}
................................................................................
   391    391   #    The tests are built on this assertion. Really, they test that the output
   392    392   #    of a CROSS JOIN, JOIN, INNER JOIN or "," join matches the expected result
   393    393   #    of calculating the cartesian product of the left and right-hand datasets. 
   394    394   #
   395    395   # EVIDENCE-OF: R-46256-57243 There is no difference between the "INNER
   396    396   # JOIN", "JOIN" and "," join operators.
   397    397   #
   398         -# EVIDENCE-OF: R-07544-24155 The "CROSS JOIN" join operator produces the
   399         -# same data as the "INNER JOIN", "JOIN" and "," operators
          398  +# EVIDENCE-OF: R-25071-21202 The "CROSS JOIN" join operator produces the
          399  +# same result as the "INNER JOIN", "JOIN" and "," operators
   400    400   #
   401    401   #    All tests are run 4 times, with the only difference in each run being
   402    402   #    which of the 4 equivalent cartesian product join operators are used.
   403    403   #    Since the output data is the same in all cases, we consider that this
   404    404   #    qualifies as testing the two statements above.
   405    405   #
   406    406   do_execsql_test e_select-1.4.0 {
................................................................................
  1222   1222     1   "SELECT ALL a FROM h1"      {1 1 1 4 4 4}
  1223   1223     2   "SELECT DISTINCT a FROM h1" {1 4}
  1224   1224   }
  1225   1225   
  1226   1226   # EVIDENCE-OF: R-08861-34280 If the simple SELECT is a SELECT ALL, then
  1227   1227   # the entire set of result rows are returned by the SELECT.
  1228   1228   #
  1229         -# EVIDENCE-OF: R-47911-02086 If neither ALL or DISTINCT are present,
         1229  +# EVIDENCE-OF: R-01256-01950 If neither ALL or DISTINCT are present,
  1230   1230   # then the behavior is as if ALL were specified.
  1231   1231   #
  1232   1232   # EVIDENCE-OF: R-14442-41305 If the simple SELECT is a SELECT DISTINCT,
  1233   1233   # then duplicate rows are removed from the set of result rows before it
  1234   1234   # is returned.
  1235   1235   #
  1236   1236   #   The three testable statements above are tested by e_select-5.2.*,

Changes to test/e_select2.test.

   348    348     # JOIN", "JOIN" or a comma (",") and there is no ON or USING clause,
   349    349     # then the result of the join is simply the cartesian product of the
   350    350     # left and right-hand datasets.
   351    351     #
   352    352     # EVIDENCE-OF: R-46256-57243 There is no difference between the "INNER
   353    353     # JOIN", "JOIN" and "," join operators.
   354    354     #
   355         -  # EVIDENCE-OF: R-07544-24155 The "CROSS JOIN" join operator produces the
   356         -  # same data as the "INNER JOIN", "JOIN" and "," operators
          355  +  # EVIDENCE-OF: R-25071-21202 The "CROSS JOIN" join operator produces the
          356  +  # same result as the "INNER JOIN", "JOIN" and "," operators
   357    357     #
   358    358     test_join $tn.1.1  "t1, t2"                {t1 t2}
   359    359     test_join $tn.1.2  "t1 INNER JOIN t2"      {t1 t2}
   360    360     test_join $tn.1.3  "t1 CROSS JOIN t2"      {t1 t2}
   361    361     test_join $tn.1.4  "t1 JOIN t2"            {t1 t2}
   362    362     test_join $tn.1.5  "t2, t3"                {t2 t3}
   363    363     test_join $tn.1.6  "t2 INNER JOIN t3"      {t2 t3}

Changes to test/e_update.test.

    45     45     CREATE TABLE aux.t5(a, b);
    46     46   } {}
    47     47   
    48     48   proc do_update_tests {args} {
    49     49     uplevel do_select_tests $args
    50     50   }
    51     51   
    52         -# EVIDENCE-OF: R-62337-45828 -- syntax diagram update-stmt
           52  +# -- syntax diagram update-stmt
    53     53   #
    54     54   do_update_tests e_update-0 {
    55     55     1    "UPDATE t1 SET a=10" {}
    56     56     2    "UPDATE t1 SET a=10, b=5" {}
    57     57     3    "UPDATE t1 SET a=10 WHERE b=5" {}
    58     58     4    "UPDATE t1 SET b=5,a=10 WHERE 1" {}
    59     59     5    "UPDATE main.t1 SET a=10" {}
................................................................................
   489    489   }
   490    490   
   491    491   # EVIDENCE-OF: R-59581-44104 If SQLite is built with the
   492    492   # SQLITE_ENABLE_UPDATE_DELETE_LIMIT compile-time option then the syntax
   493    493   # of the UPDATE statement is extended with optional ORDER BY and LIMIT
   494    494   # clauses
   495    495   #
   496         -# EVIDENCE-OF: R-45169-39597 -- syntax diagram update-stmt-limited
          496  +# -- syntax diagram update-stmt-limited
   497    497   #
   498    498   do_update_tests e_update-3.0 {
   499    499     1   "UPDATE t1 SET a=b LIMIT 5"                                    {}
   500    500     2   "UPDATE t1 SET a=b LIMIT 5-1 OFFSET 2+2"                       {}
   501    501     3   "UPDATE t1 SET a=b LIMIT 2+2, 16/4"                            {}
   502    502     4   "UPDATE t1 SET a=b ORDER BY a LIMIT 5"                         {}
   503    503     5   "UPDATE t1 SET a=b ORDER BY a LIMIT 5-1 OFFSET 2+2"            {}

Changes to test/e_uri.test.

   353    353   # EVIDENCE-OF: R-23027-03515 Setting it to "shared" is equivalent to
   354    354   # setting the SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed
   355    355   # to sqlite3_open_v2().
   356    356   #
   357    357   # EVIDENCE-OF: R-49793-28525 Setting the cache parameter to "private" is
   358    358   # equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
   359    359   #
   360         -# EVIDENCE-OF: R-19510-48080 If sqlite3_open_v2() is used and the
          360  +# EVIDENCE-OF: R-31773-41793 If sqlite3_open_v2() is used and the
   361    361   # "cache" parameter is present in a URI filename, its value overrides
   362    362   # any behavior requested by setting SQLITE_OPEN_PRIVATECACHE or
   363    363   # SQLITE_OPEN_SHAREDCACHE flag.
   364    364   #
   365    365   set orig [sqlite3_enable_shared_cache]
   366    366   foreach {tn uri flags shared_default isshared} {
   367    367     1.1   "file:test.db"                  ""         0    0

Changes to test/e_vacuum.test.

    61     61       set prevpageno $pageno
    62     62     }
    63     63     execsql { DROP TABLE temp.stat }
    64     64     set nFrag
    65     65   }
    66     66   
    67     67   
    68         -# EVIDENCE-OF: R-45173-45977 -- syntax diagram vacuum-stmt
           68  +# -- syntax diagram vacuum-stmt
    69     69   #
    70     70   do_execsql_test e_vacuum-0.1 { VACUUM } {}
    71     71   
    72     72   # EVIDENCE-OF: R-51469-36013 Unless SQLite is running in
    73     73   # "auto_vacuum=FULL" mode, when a large amount of data is deleted from
    74     74   # the database file it leaves behind empty space, or "free" database
    75     75   # pages.

Changes to test/eqp.test.

   366    366   
   367    367   #-------------------------------------------------------------------------
   368    368   # This next block of tests verifies that the examples on the 
   369    369   # lang_explain.html page are correct.
   370    370   #
   371    371   drop_all_tables
   372    372   
   373         -# EVIDENCE-OF: R-64208-08323 sqlite> EXPLAIN QUERY PLAN SELECT a, b
   374         -# FROM t1 WHERE a=1; 0|0|0|SCAN TABLE t1
          373  +# EVIDENCE-OF: R-47779-47605 sqlite> EXPLAIN QUERY PLAN SELECT a, b
          374  +# FROM t1 WHERE a=1;
          375  +# 0|0|0|SCAN TABLE t1
          376  +#
   375    377   do_execsql_test 5.1.0 { CREATE TABLE t1(a, b) }
   376    378   det 5.1.1 "SELECT a, b FROM t1 WHERE a=1" {
   377    379     0 0 0 {SCAN TABLE t1}
   378    380   }
   379    381   
   380         -# EVIDENCE-OF: R-09022-44606 sqlite> CREATE INDEX i1 ON t1(a);
          382  +# EVIDENCE-OF: R-55852-17599 sqlite> CREATE INDEX i1 ON t1(a);
   381    383   # sqlite> EXPLAIN QUERY PLAN SELECT a, b FROM t1 WHERE a=1;
   382         -# 0|0|0|SEARCH TABLE t1 USING INDEX i1 (a=?)
          384  +# 0|0|0|SEARCH TABLE t1 USING INDEX i1
          385  +#
   383    386   do_execsql_test 5.2.0 { CREATE INDEX i1 ON t1(a) }
   384    387   det 5.2.1 "SELECT a, b FROM t1 WHERE a=1" {
   385    388     0 0 0 {SEARCH TABLE t1 USING INDEX i1 (a=?)}
   386    389   }
   387    390   
   388         -# EVIDENCE-OF: R-62228-34103 sqlite> CREATE INDEX i2 ON t1(a, b);
          391  +# EVIDENCE-OF: R-21179-11011 sqlite> CREATE INDEX i2 ON t1(a, b);
   389    392   # sqlite> EXPLAIN QUERY PLAN SELECT a, b FROM t1 WHERE a=1;
   390    393   # 0|0|0|SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)
          394  +#
   391    395   do_execsql_test 5.3.0 { CREATE INDEX i2 ON t1(a, b) }
   392    396   det 5.3.1 "SELECT a, b FROM t1 WHERE a=1" {
   393    397     0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)}
   394    398   }
   395    399   
   396         -# EVIDENCE-OF: R-22253-05302 sqlite> EXPLAIN QUERY PLAN SELECT t1.*,
   397         -# t2.* FROM t1, t2 WHERE t1.a=1 AND t1.b>2; 0|0|0|SEARCH TABLE t1
   398         -# USING COVERING INDEX i2 (a=? AND b>?) 0|1|1|SCAN TABLE t2
          400  +# EVIDENCE-OF: R-09991-48941 sqlite> EXPLAIN QUERY PLAN
          401  +# SELECT t1.*, t2.* FROM t1, t2 WHERE t1.a=1 AND t1.b>2;
          402  +# 0|0|0|SEARCH TABLE t1 USING COVERING INDEX i2 (a=? AND b>?)
          403  +# 0|1|1|SCAN TABLE t2
   399    404   #
   400    405   do_execsql_test 5.4.0 {CREATE TABLE t2(c, d)}
   401    406   det 5.4.1 "SELECT t1.*, t2.* FROM t1, t2 WHERE t1.a=1 AND t1.b>2" {
   402    407     0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=? AND b>?)}
   403    408     0 1 1 {SCAN TABLE t2}
   404    409   }
   405    410   
   406         -# EVIDENCE-OF: R-21040-07025 sqlite> EXPLAIN QUERY PLAN SELECT t1.*,
   407         -# t2.* FROM t2, t1 WHERE t1.a=1 AND t1.b>2; 0|0|1|SEARCH TABLE t1
   408         -# USING COVERING INDEX i2 (a=? AND b>?) 0|1|0|SCAN TABLE t2
          411  +# EVIDENCE-OF: R-33626-61085 sqlite> EXPLAIN QUERY PLAN
          412  +# SELECT t1.*, t2.* FROM t2, t1 WHERE t1.a=1 AND t1.b>2;
          413  +# 0|0|1|SEARCH TABLE t1 USING COVERING INDEX i2 (a=? AND b>?)
          414  +# 0|1|0|SCAN TABLE t2
   409    415   #
   410    416   det 5.5 "SELECT t1.*, t2.* FROM t2, t1 WHERE t1.a=1 AND t1.b>2" {
   411    417     0 0 1 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=? AND b>?)}
   412    418     0 1 0 {SCAN TABLE t2}
   413    419   }
   414    420   
   415         -# EVIDENCE-OF: R-39007-61103 sqlite> CREATE INDEX i3 ON t1(b);
          421  +# EVIDENCE-OF: R-04002-25654 sqlite> CREATE INDEX i3 ON t1(b);
   416    422   # sqlite> EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE a=1 OR b=2;
   417    423   # 0|0|0|SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)
   418    424   # 0|0|0|SEARCH TABLE t1 USING INDEX i3 (b=?)
          425  +#
   419    426   do_execsql_test 5.5.0 {CREATE INDEX i3 ON t1(b)}
   420    427   det 5.6.1 "SELECT * FROM t1 WHERE a=1 OR b=2" {
   421    428     0 0 0 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)}
   422    429     0 0 0 {SEARCH TABLE t1 USING INDEX i3 (b=?)}
   423    430   }
   424    431   
   425         -# EVIDENCE-OF: R-33025-54904 sqlite> EXPLAIN QUERY PLAN SELECT c, d
   426         -# FROM t2 ORDER BY c; 0|0|0|SCAN TABLE t2 0|0|0|USE TEMP
   427         -# B-TREE FOR ORDER BY
          432  +# EVIDENCE-OF: R-24577-38891 sqlite> EXPLAIN QUERY PLAN
          433  +# SELECT c, d FROM t2 ORDER BY c;
          434  +# 0|0|0|SCAN TABLE t2
          435  +# 0|0|0|USE TEMP B-TREE FOR ORDER BY
          436  +#
   428    437   det 5.7 "SELECT c, d FROM t2 ORDER BY c" {
   429    438     0 0 0 {SCAN TABLE t2}
   430    439     0 0 0 {USE TEMP B-TREE FOR ORDER BY}
   431    440   }
   432    441   
   433         -# EVIDENCE-OF: R-38854-22809 sqlite> CREATE INDEX i4 ON t2(c);
          442  +# EVIDENCE-OF: R-58157-12355 sqlite> CREATE INDEX i4 ON t2(c);
   434    443   # sqlite> EXPLAIN QUERY PLAN SELECT c, d FROM t2 ORDER BY c;
   435    444   # 0|0|0|SCAN TABLE t2 USING INDEX i4
          445  +#
   436    446   do_execsql_test 5.8.0 {CREATE INDEX i4 ON t2(c)}
   437    447   det 5.8.1 "SELECT c, d FROM t2 ORDER BY c" {
   438    448     0 0 0 {SCAN TABLE t2 USING INDEX i4}
   439    449   }
   440    450   
   441         -# EVIDENCE-OF: R-29884-43993 sqlite> EXPLAIN QUERY PLAN SELECT
          451  +# EVIDENCE-OF: R-13931-10421 sqlite> EXPLAIN QUERY PLAN SELECT
   442    452   # (SELECT b FROM t1 WHERE a=0), (SELECT a FROM t1 WHERE b=t2.c) FROM t2;
   443         -# 0|0|0|SCAN TABLE t2 0|0|0|EXECUTE SCALAR SUBQUERY 1
          453  +# 0|0|0|SCAN TABLE t2
          454  +# 0|0|0|EXECUTE SCALAR SUBQUERY 1
   444    455   # 1|0|0|SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)
   445         -# 0|0|0|EXECUTE CORRELATED SCALAR SUBQUERY 2 2|0|0|SEARCH TABLE t1 USING
   446         -# INDEX i3 (b=?)
          456  +# 0|0|0|EXECUTE CORRELATED SCALAR SUBQUERY 2
          457  +# 2|0|0|SEARCH TABLE t1 USING INDEX i3 (b=?)
          458  +#
   447    459   det 5.9 {
   448    460     SELECT (SELECT b FROM t1 WHERE a=0), (SELECT a FROM t1 WHERE b=t2.c) FROM t2
   449    461   } {
   450    462     0 0 0 {SCAN TABLE t2 USING COVERING INDEX i4}
   451    463     0 0 0 {EXECUTE SCALAR SUBQUERY 1}
   452    464     1 0 0 {SEARCH TABLE t1 USING COVERING INDEX i2 (a=?)}
   453    465     0 0 0 {EXECUTE CORRELATED SCALAR SUBQUERY 2}
   454    466     2 0 0 {SEARCH TABLE t1 USING INDEX i3 (b=?)}
   455    467   }
   456    468   
   457         -# EVIDENCE-OF: R-17911-16445 sqlite> EXPLAIN QUERY PLAN SELECT
   458         -# count(*) FROM (SELECT max(b) AS x FROM t1 GROUP BY a) GROUP BY x;
   459         -# 1|0|0|SCAN TABLE t1 USING COVERING INDEX i2 0|0|0|SCAN
   460         -# SUBQUERY 1 0|0|0|USE TEMP B-TREE FOR GROUP BY
          469  +# EVIDENCE-OF: R-50892-45943 sqlite> EXPLAIN QUERY PLAN
          470  +# SELECT count(*) FROM (SELECT max(b) AS x FROM t1 GROUP BY a) GROUP BY x;
          471  +# 1|0|0|SCAN TABLE t1 USING COVERING INDEX i2
          472  +# 0|0|0|SCAN SUBQUERY 1
          473  +# 0|0|0|USE TEMP B-TREE FOR GROUP BY
          474  +#
   461    475   det 5.10 {
   462    476     SELECT count(*) FROM (SELECT max(b) AS x FROM t1 GROUP BY a) GROUP BY x
   463    477   } {
   464    478     1 0 0 {SCAN TABLE t1 USING COVERING INDEX i2}
   465    479     0 0 0 {SCAN SUBQUERY 1}
   466    480     0 0 0 {USE TEMP B-TREE FOR GROUP BY}
   467    481   }
   468    482   
   469         -# EVIDENCE-OF: R-18544-33103 sqlite> EXPLAIN QUERY PLAN SELECT * FROM
   470         -# (SELECT * FROM t2 WHERE c=1), t1; 0|0|0|SEARCH TABLE t2 USING INDEX i4
   471         -# (c=?) 0|1|1|SCAN TABLE t1
          483  +# EVIDENCE-OF: R-46219-33846 sqlite> EXPLAIN QUERY PLAN
          484  +# SELECT * FROM (SELECT * FROM t2 WHERE c=1), t1;
          485  +# 0|0|0|SEARCH TABLE t2 USING INDEX i4 (c=?)
          486  +# 0|1|1|SCAN TABLE t1
          487  +#
   472    488   det 5.11 "SELECT * FROM (SELECT * FROM t2 WHERE c=1), t1" {
   473    489     0 0 0 {SEARCH TABLE t2 USING INDEX i4 (c=?)}
   474    490     0 1 1 {SCAN TABLE t1 USING COVERING INDEX i2}
   475    491   }
   476    492   
   477         -# EVIDENCE-OF: R-40701-42164 sqlite> EXPLAIN QUERY PLAN SELECT a FROM
   478         -# t1 UNION SELECT c FROM t2; 1|0|0|SCAN TABLE t1
   479         -# 2|0|0|SCAN TABLE t2 0|0|0|COMPOUND SUBQUERIES 1 AND 2
   480         -# USING TEMP B-TREE (UNION)
          493  +# EVIDENCE-OF: R-37879-39987 sqlite> EXPLAIN QUERY PLAN
          494  +# SELECT a FROM t1 UNION SELECT c FROM t2;
          495  +# 1|0|0|SCAN TABLE t1
          496  +# 2|0|0|SCAN TABLE t2
          497  +# 0|0|0|COMPOUND SUBQUERIES 1 AND 2 USING TEMP B-TREE (UNION)
          498  +#
   481    499   det 5.12 "SELECT a FROM t1 UNION SELECT c FROM t2" {
   482    500     1 0 0 {SCAN TABLE t1 USING COVERING INDEX i2}
   483    501     2 0 0 {SCAN TABLE t2 USING COVERING INDEX i4}
   484    502     0 0 0 {COMPOUND SUBQUERIES 1 AND 2 USING TEMP B-TREE (UNION)}
   485    503   }
   486    504   
   487         -# EVIDENCE-OF: R-61538-24748 sqlite> EXPLAIN QUERY PLAN SELECT a FROM
   488         -# t1 EXCEPT SELECT d FROM t2 ORDER BY 1; 1|0|0|SCAN TABLE t1 USING
   489         -# COVERING INDEX i2 2|0|0|SCAN TABLE t2
   490         -# 2|0|0|USE TEMP B-TREE FOR ORDER BY 0|0|0|COMPOUND SUBQUERIES 1 AND 2
   491         -# (EXCEPT)
          505  +# EVIDENCE-OF: R-44864-63011 sqlite> EXPLAIN QUERY PLAN
          506  +# SELECT a FROM t1 EXCEPT SELECT d FROM t2 ORDER BY 1;
          507  +# 1|0|0|SCAN TABLE t1 USING COVERING INDEX i2
          508  +# 2|0|0|SCAN TABLE t2 2|0|0|USE TEMP B-TREE FOR ORDER BY
          509  +# 0|0|0|COMPOUND SUBQUERIES 1 AND 2 (EXCEPT)
          510  +#
   492    511   det 5.13 "SELECT a FROM t1 EXCEPT SELECT d FROM t2 ORDER BY 1" {
   493    512     1 0 0 {SCAN TABLE t1 USING COVERING INDEX i2}
   494    513     2 0 0 {SCAN TABLE t2}
   495    514     2 0 0 {USE TEMP B-TREE FOR ORDER BY}
   496    515     0 0 0 {COMPOUND SUBQUERIES 1 AND 2 (EXCEPT)}
   497    516   }
   498    517   

Changes to test/index.test.

   711    711     }
   712    712   } {}
   713    713   do_test index-20.2 {
   714    714     execsql {
   715    715       DROP INDEX "t6i1";
   716    716     }
   717    717   } {}
          718  +
          719  +# Try to create a TEMP index on a non-TEMP table. */
          720  +#
          721  +do_test index-21.1 {
          722  +  catchsql {
          723  +     CREATE INDEX temp.i21 ON t6(c);
          724  +  }
          725  +} {1 {cannot create a TEMP index on non-TEMP table "t6"}}
          726  +do_test index-21.2 {
          727  +  catchsql {
          728  +     CREATE TEMP TABLE t6(x);
          729  +     INSERT INTO temp.t6 values(1),(5),(9);
          730  +     CREATE INDEX temp.i21 ON t6(x);
          731  +     SELECT x FROM t6 ORDER BY x DESC;
          732  +  }
          733  +} {0 {9 5 1}}
          734  +
   718    735      
   719    736   
   720    737   finish_test

Added test/index6.test.

            1  +# 2013-07-31
            2  +#
            3  +# The author disclaims copyright to this source code.  In place of
            4  +# a legal notice, here is a blessing:
            5  +#
            6  +#    May you do good and not evil.
            7  +#    May you find forgiveness for yourself and forgive others.
            8  +#    May you share freely, never taking more than you give.
            9  +#
           10  +#***********************************************************************
           11  +#
           12  +# Test cases for partial indices
           13  +#
           14  +
           15  +
           16  +set testdir [file dirname $argv0]
           17  +source $testdir/tester.tcl
           18  +
           19  +load_static_extension db wholenumber;
           20  +do_test index6-1.1 {
           21  +  # Able to parse and manage partial indices
           22  +  execsql {
           23  +    CREATE TABLE t1(a,b,c);
           24  +    CREATE INDEX t1a ON t1(a) WHERE a IS NOT NULL;
           25  +    CREATE INDEX t1b ON t1(b) WHERE b>10;
           26  +    CREATE VIRTUAL TABLE nums USING wholenumber;
           27  +    INSERT INTO t1(a,b,c)
           28  +       SELECT CASE WHEN value%3!=0 THEN value END, value, value
           29  +         FROM nums WHERE value<=20;
           30  +    SELECT count(a), count(b) FROM t1;
           31  +    PRAGMA integrity_check;
           32  +  }
           33  +} {14 20 ok}
           34  +
           35  +# Error conditions during parsing...
           36  +#
           37  +do_test index6-1.2 {
           38  +  catchsql {
           39  +    CREATE INDEX bad1 ON t1(a,b) WHERE x IS NOT NULL;
           40  +  }
           41  +} {1 {no such column: x}}
           42  +do_test index6-1.3 {
           43  +  catchsql {
           44  +    CREATE INDEX bad1 ON t1(a,b) WHERE EXISTS(SELECT * FROM t1);
           45  +  }
           46  +} {1 {subqueries prohibited in partial index WHERE clauses}}
           47  +do_test index6-1.4 {
           48  +  catchsql {
           49  +    CREATE INDEX bad1 ON t1(a,b) WHERE a!=?1;
           50  +  }
           51  +} {1 {parameters prohibited in partial index WHERE clauses}}
           52  +do_test index6-1.5 {
           53  +  catchsql {
           54  +    CREATE INDEX bad1 ON t1(a,b) WHERE a!=random();
           55  +  }
           56  +} {1 {functions prohibited in partial index WHERE clauses}}
           57  +do_test index6-1.6 {
           58  +  catchsql {
           59  +    CREATE INDEX bad1 ON t1(a,b) WHERE a NOT LIKE 'abc%';
           60  +  }
           61  +} {1 {functions prohibited in partial index WHERE clauses}}
           62  +
           63  +do_test index6-1.10 {
           64  +  execsql {
           65  +    ANALYZE;
           66  +    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
           67  +    PRAGMA integrity_check;
           68  +  }
           69  +} {{} 20 t1a {14 1} t1b {10 1} ok}
           70  +
           71  +# STAT1 shows the partial indices have a reduced number of
           72  +# rows.
           73  +#
           74  +do_test index6-1.11 {
           75  +  execsql {
           76  +    UPDATE t1 SET a=b;
           77  +    ANALYZE;
           78  +    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
           79  +    PRAGMA integrity_check;
           80  +  }
           81  +} {{} 20 t1a {20 1} t1b {10 1} ok}
           82  +
           83  +do_test index6-1.11 {
           84  +  execsql {
           85  +    UPDATE t1 SET a=NULL WHERE b%3!=0;
           86  +    UPDATE t1 SET b=b+100;
           87  +    ANALYZE;
           88  +    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
           89  +    PRAGMA integrity_check;
           90  +  }
           91  +} {{} 20 t1a {6 1} t1b {20 1} ok}
           92  +
           93  +do_test index6-1.12 {
           94  +  execsql {
           95  +    UPDATE t1 SET a=CASE WHEN b%3!=0 THEN b END;
           96  +    UPDATE t1 SET b=b-100;
           97  +    ANALYZE;
           98  +    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
           99  +    PRAGMA integrity_check;
          100  +  }
          101  +} {{} 20 t1a {13 1} t1b {10 1} ok}
          102  +
          103  +do_test index6-1.13 {
          104  +  execsql {
          105  +    DELETE FROM t1 WHERE b BETWEEN 8 AND 12;
          106  +    ANALYZE;
          107  +    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
          108  +    PRAGMA integrity_check;
          109  +  }
          110  +} {{} 15 t1a {10 1} t1b {8 1} ok}
          111  +
          112  +do_test index6-1.14 {
          113  +  execsql {
          114  +    REINDEX;
          115  +    ANALYZE;
          116  +    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
          117  +    PRAGMA integrity_check;
          118  +  }
          119  +} {{} 15 t1a {10 1} t1b {8 1} ok}
          120  +
          121  +do_test index6-1.15 {
          122  +  execsql {
          123  +    CREATE INDEX t1c ON t1(c);
          124  +    ANALYZE;
          125  +    SELECT idx, stat FROM sqlite_stat1 ORDER BY idx;
          126  +    PRAGMA integrity_check;
          127  +  }
          128  +} {t1a {10 1} t1b {8 1} t1c {15 1} ok}
          129  +
          130  +# Queries use partial indices as appropriate times.
          131  +#
          132  +do_test index6-2.1 {
          133  +  execsql {
          134  +    CREATE TABLE t2(a,b);
          135  +    INSERT INTO t2(a,b) SELECT value, value FROM nums WHERE value<1000;
          136  +    UPDATE t2 SET a=NULL WHERE b%5==0;
          137  +    CREATE INDEX t2a1 ON t2(a) WHERE a IS NOT NULL;
          138  +    SELECT count(*) FROM t2 WHERE a IS NOT NULL;
          139  +  }
          140  +} {800}
          141  +do_test index6-2.2 {
          142  +  execsql {
          143  +    EXPLAIN QUERY PLAN
          144  +    SELECT * FROM t2 WHERE a=5;
          145  +  }
          146  +} {/.* TABLE t2 USING INDEX t2a1 .*/}
          147  +ifcapable stat3 {
          148  +  do_test index6-2.3stat3 {
          149  +    execsql {
          150  +      EXPLAIN QUERY PLAN
          151  +      SELECT * FROM t2 WHERE a IS NOT NULL;
          152  +    }
          153  +  } {/.* TABLE t2 USING INDEX t2a1 .*/}
          154  +} else {
          155  +  do_test index6-2.3stat3 {
          156  +    execsql {
          157  +      EXPLAIN QUERY PLAN
          158  +      SELECT * FROM t2 WHERE a IS NOT NULL AND a>0;
          159  +    }
          160  +  } {/.* TABLE t2 USING INDEX t2a1 .*/}
          161  +}
          162  +do_test index6-2.4 {
          163  +  execsql {
          164  +    EXPLAIN QUERY PLAN
          165  +    SELECT * FROM t2 WHERE a IS NULL;
          166  +  }
          167  +} {~/.*INDEX t2a1.*/}
          168  +
          169  +do_execsql_test index6-2.101 {
          170  +  DROP INDEX t2a1;
          171  +  UPDATE t2 SET a=b, b=b+10000;
          172  +  SELECT b FROM t2 WHERE a=15;
          173  +} {10015}
          174  +do_execsql_test index6-2.102 {
          175  +  CREATE INDEX t2a2 ON t2(a) WHERE a<100 OR a>200;
          176  +  SELECT b FROM t2 WHERE a=15;
          177  +  PRAGMA integrity_check;
          178  +} {10015 ok}
          179  +do_execsql_test index6-2.102eqp {
          180  +  EXPLAIN QUERY PLAN
          181  +  SELECT b FROM t2 WHERE a=15;
          182  +} {~/.*INDEX t2a2.*/}
          183  +do_execsql_test index6-2.103 {
          184  +  SELECT b FROM t2 WHERE a=15 AND a<100;
          185  +} {10015}
          186  +do_execsql_test index6-2.103eqp {
          187  +  EXPLAIN QUERY PLAN
          188  +  SELECT b FROM t2 WHERE a=15 AND a<100;
          189  +} {/.*INDEX t2a2.*/}
          190  +do_execsql_test index6-2.104 {
          191  +  SELECT b FROM t2 WHERE a=515 AND a>200;
          192  +} {10515}
          193  +do_execsql_test index6-2.104eqp {
          194  +  EXPLAIN QUERY PLAN
          195  +  SELECT b FROM t2 WHERE a=515 AND a>200;
          196  +} {/.*INDEX t2a2.*/}
          197  +
          198  +# Partial UNIQUE indices
          199  +#
          200  +do_execsql_test index6-3.1 {
          201  +  CREATE TABLE t3(a,b);
          202  +  INSERT INTO t3 SELECT value, value FROM nums WHERE value<200;
          203  +  UPDATE t3 SET a=999 WHERE b%5!=0;
          204  +  CREATE UNIQUE INDEX t3a ON t3(a) WHERE a<>999;
          205  +} {}
          206  +do_test index6-3.2 {
          207  +  # unable to insert a duplicate row a-value that is not 999.
          208  +  catchsql {
          209  +    INSERT INTO t3(a,b) VALUES(150, 'test1');
          210  +  }
          211  +} {1 {column a is not unique}}
          212  +do_test index6-3.3 {
          213  +  # can insert multiple rows with a==999 because such rows are not
          214  +  # part of the unique index.
          215  +  catchsql {
          216  +    INSERT INTO t3(a,b) VALUES(999, 'test1'), (999, 'test2');
          217  +  }
          218  +} {0 {}}
          219  +do_execsql_test index6-3.4 {
          220  +  SELECT count(*) FROM t3 WHERE a=999;
          221  +} {162}
          222  +integrity_check index6-3.5
          223  +
          224  +do_execsql_test index6-4.0 {
          225  +  VACUUM;
          226  +  PRAGMA integrity_check;
          227  +} {ok}
          228  +
          229  +# Silently ignore database name qualifiers in partial indices.
          230  +#
          231  +do_execsql_test index6-5.0 {
          232  +  CREATE INDEX t3b ON t3(b) WHERE xyzzy.t3.b BETWEEN 5 AND 10;
          233  +                               /* ^^^^^-- ignored */
          234  +  ANALYZE;
          235  +  SELECT count(*) FROM t3 WHERE t3.b BETWEEN 5 AND 10;
          236  +  SELECT stat+0 FROM sqlite_stat1 WHERE idx='t3b';
          237  +} {6 6}
          238  +
          239  +finish_test