/ Check-in [497367cb]
Login

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

Overview
Comment:Merge recent trunk changes (performance enhancements) into the sessions branch.
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | sessions
Files: files | file ages | folders
SHA1: 497367cb57345dd37793e5f369b34d12be56172e
User & Date: drh 2014-09-27 19:51:50
Context
2014-09-27
20:45
Change the names of the stream interface APIs to be of the form "_strm" instead of "_str". In other words, added an "m" to the end, to try to make it clear that we are talking about a "stream" and not a "string. check-in: 1f44bfdc user: drh tags: sessions
19:51
Merge recent trunk changes (performance enhancements) into the sessions branch. check-in: 497367cb user: drh tags: sessions
18:18
Fix a segfault in the sessions module that could follow an OOM. check-in: 09985fa6 user: dan tags: sessions
2014-09-26
18:30
Add an assert() to verify the last-row-id for the database just prior to calling a SQL function. check-in: d026f0c9 user: mistachkin tags: trunk
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to src/btree.c.

   483    483     i64 iRow,               /* The rowid that might be changing */
   484    484     int isClearTable        /* True if all rows are being deleted */
   485    485   ){
   486    486     BtCursor *p;
   487    487     BtShared *pBt = pBtree->pBt;
   488    488     assert( sqlite3BtreeHoldsMutex(pBtree) );
   489    489     for(p=pBt->pCursor; p; p=p->pNext){
   490         -    if( (p->curFlags & BTCF_Incrblob)!=0 && (isClearTable || p->info.nKey==iRow) ){
          490  +    if( (p->curFlags & BTCF_Incrblob)!=0
          491  +     && (isClearTable || p->info.nKey==iRow)
          492  +    ){
   491    493         p->eState = CURSOR_INVALID;
   492    494       }
   493    495     }
   494    496   }
   495    497   
   496    498   #else
   497    499     /* Stub function when INCRBLOB is omitted */
................................................................................
   656    658   
   657    659   /* This helper routine to saveAllCursors does the actual work of saving
   658    660   ** the cursors if and when a cursor is found that actually requires saving.
   659    661   ** The common case is that no cursors need to be saved, so this routine is
   660    662   ** broken out from its caller to avoid unnecessary stack pointer movement.
   661    663   */
   662    664   static int SQLITE_NOINLINE saveCursorsOnList(
   663         -  BtCursor *p,           /* The first cursor that needs saving */
   664         -  Pgno iRoot,            /* Only save cursor with this iRoot.  Save all if zero */
   665         -  BtCursor *pExcept      /* Do not save this cursor */
          665  +  BtCursor *p,         /* The first cursor that needs saving */
          666  +  Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
          667  +  BtCursor *pExcept    /* Do not save this cursor */
   666    668   ){
   667    669     do{
   668    670       if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
   669    671         if( p->eState==CURSOR_VALID ){
   670    672           int rc = saveCursorPosition(p);
   671    673           if( SQLITE_OK!=rc ){
   672    674             return rc;
................................................................................
   964    966   }
   965    967   
   966    968   /*
   967    969   ** Parse a cell content block and fill in the CellInfo structure.  There
   968    970   ** are two versions of this function.  btreeParseCell() takes a 
   969    971   ** cell index as the second argument and btreeParseCellPtr() 
   970    972   ** takes a pointer to the body of the cell as its second argument.
   971         -**
   972         -** Within this file, the parseCell() macro can be called instead of
   973         -** btreeParseCellPtr(). Using some compilers, this will be faster.
   974    973   */
   975    974   static void btreeParseCellPtr(
   976    975     MemPage *pPage,         /* Page containing the cell */
   977    976     u8 *pCell,              /* Pointer to the cell text. */
   978    977     CellInfo *pInfo         /* Fill in this structure */
   979    978   ){
   980         -  u16 n;                  /* Number bytes in cell content header */
          979  +  u8 *pIter;              /* For scanning through pCell */
   981    980     u32 nPayload;           /* Number of bytes of cell payload */
   982    981   
   983    982     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
   984         -
   985         -  pInfo->pCell = pCell;
   986    983     assert( pPage->leaf==0 || pPage->leaf==1 );
   987         -  n = pPage->childPtrSize;
   988         -  assert( n==4-4*pPage->leaf );
   989         -  if( pPage->intKey ){
   990         -    if( pPage->hasData ){
   991         -      assert( n==0 );
   992         -      n = getVarint32(pCell, nPayload);
   993         -    }else{
   994         -      nPayload = 0;
   995         -    }
   996         -    n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
   997         -    pInfo->nData = nPayload;
          984  +  if( pPage->intKeyLeaf ){
          985  +    assert( pPage->childPtrSize==0 );
          986  +    pIter = pCell + getVarint32(pCell, nPayload);
          987  +    pIter += getVarint(pIter, (u64*)&pInfo->nKey);
          988  +  }else if( pPage->noPayload ){
          989  +    assert( pPage->childPtrSize==4 );
          990  +    pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
          991  +    pInfo->nPayload = 0;
          992  +    pInfo->nLocal = 0;
          993  +    pInfo->iOverflow = 0;
          994  +    pInfo->pPayload = 0;
          995  +    return;
   998    996     }else{
   999         -    pInfo->nData = 0;
  1000         -    n += getVarint32(&pCell[n], nPayload);
          997  +    pIter = pCell + pPage->childPtrSize;
          998  +    pIter += getVarint32(pIter, nPayload);
  1001    999       pInfo->nKey = nPayload;
  1002   1000     }
  1003   1001     pInfo->nPayload = nPayload;
  1004         -  pInfo->nHeader = n;
         1002  +  pInfo->pPayload = pIter;
  1005   1003     testcase( nPayload==pPage->maxLocal );
  1006   1004     testcase( nPayload==pPage->maxLocal+1 );
  1007         -  if( likely(nPayload<=pPage->maxLocal) ){
         1005  +  if( nPayload<=pPage->maxLocal ){
  1008   1006       /* This is the (easy) common case where the entire payload fits
  1009   1007       ** on the local page.  No overflow is required.
  1010   1008       */
  1011         -    if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
         1009  +    pInfo->nSize = nPayload + (u16)(pIter - pCell);
         1010  +    if( pInfo->nSize<4 ) pInfo->nSize = 4;
  1012   1011       pInfo->nLocal = (u16)nPayload;
  1013   1012       pInfo->iOverflow = 0;
  1014   1013     }else{
  1015   1014       /* If the payload will not fit completely on the local page, we have
  1016   1015       ** to decide how much to store locally and how much to spill onto
  1017   1016       ** overflow pages.  The strategy is to minimize the amount of unused
  1018   1017       ** space on overflow pages while keeping the amount of local storage
................................................................................
  1031   1030       testcase( surplus==maxLocal );
  1032   1031       testcase( surplus==maxLocal+1 );
  1033   1032       if( surplus <= maxLocal ){
  1034   1033         pInfo->nLocal = (u16)surplus;
  1035   1034       }else{
  1036   1035         pInfo->nLocal = (u16)minLocal;
  1037   1036       }
  1038         -    pInfo->iOverflow = (u16)(pInfo->nLocal + n);
         1037  +    pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
  1039   1038       pInfo->nSize = pInfo->iOverflow + 4;
  1040   1039     }
  1041   1040   }
  1042         -#define parseCell(pPage, iCell, pInfo) \
  1043         -  btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  1044   1041   static void btreeParseCell(
  1045   1042     MemPage *pPage,         /* Page containing the cell */
  1046   1043     int iCell,              /* The cell index.  First cell is 0 */
  1047   1044     CellInfo *pInfo         /* Fill in this structure */
  1048   1045   ){
  1049         -  parseCell(pPage, iCell, pInfo);
         1046  +  btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
  1050   1047   }
  1051   1048   
  1052   1049   /*
  1053   1050   ** Compute the total number of bytes that a Cell needs in the cell
  1054   1051   ** data area of the btree-page.  The return number includes the cell
  1055   1052   ** data header and the local payload, but not any overflow page or
  1056   1053   ** the space used by the cell pointer.
  1057   1054   */
  1058   1055   static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  1059         -  u8 *pIter = &pCell[pPage->childPtrSize];
  1060         -  u32 nSize;
         1056  +  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
         1057  +  u8 *pEnd;                                /* End mark for a varint */
         1058  +  u32 nSize;                               /* Size value to return */
  1061   1059   
  1062   1060   #ifdef SQLITE_DEBUG
  1063   1061     /* The value returned by this function should always be the same as
  1064   1062     ** the (CellInfo.nSize) value found by doing a full parse of the
  1065   1063     ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  1066   1064     ** this function verifies that this invariant is not violated. */
  1067   1065     CellInfo debuginfo;
  1068   1066     btreeParseCellPtr(pPage, pCell, &debuginfo);
  1069   1067   #endif
  1070   1068   
         1069  +  if( pPage->noPayload ){
         1070  +    pEnd = &pIter[9];
         1071  +    while( (*pIter++)&0x80 && pIter<pEnd );
         1072  +    assert( pPage->childPtrSize==4 );
         1073  +    return (u16)(pIter - pCell);
         1074  +  }
         1075  +  nSize = *pIter;
         1076  +  if( nSize>=0x80 ){
         1077  +    pEnd = &pIter[9];
         1078  +    nSize &= 0x7f;
         1079  +    do{
         1080  +      nSize = (nSize<<7) | (*++pIter & 0x7f);
         1081  +    }while( *(pIter)>=0x80 && pIter<pEnd );
         1082  +  }
         1083  +  pIter++;
  1071   1084     if( pPage->intKey ){
  1072         -    u8 *pEnd;
  1073         -    if( pPage->hasData ){
  1074         -      pIter += getVarint32(pIter, nSize);
  1075         -    }else{
  1076         -      nSize = 0;
  1077         -    }
  1078         -
  1079   1085       /* pIter now points at the 64-bit integer key value, a variable length 
  1080   1086       ** integer. The following block moves pIter to point at the first byte
  1081   1087       ** past the end of the key value. */
  1082   1088       pEnd = &pIter[9];
  1083   1089       while( (*pIter++)&0x80 && pIter<pEnd );
  1084         -  }else{
  1085         -    pIter += getVarint32(pIter, nSize);
  1086   1090     }
  1087         -
  1088   1091     testcase( nSize==pPage->maxLocal );
  1089   1092     testcase( nSize==pPage->maxLocal+1 );
  1090         -  if( nSize>pPage->maxLocal ){
         1093  +  if( nSize<=pPage->maxLocal ){
         1094  +    nSize += (u32)(pIter - pCell);
         1095  +    if( nSize<4 ) nSize = 4;
         1096  +  }else{
  1091   1097       int minLocal = pPage->minLocal;
  1092   1098       nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  1093   1099       testcase( nSize==pPage->maxLocal );
  1094   1100       testcase( nSize==pPage->maxLocal+1 );
  1095   1101       if( nSize>pPage->maxLocal ){
  1096   1102         nSize = minLocal;
  1097   1103       }
  1098         -    nSize += 4;
         1104  +    nSize += 4 + (u16)(pIter - pCell);
  1099   1105     }
  1100         -  nSize += (u32)(pIter - pCell);
  1101         -
  1102         -  /* The minimum size of any cell is 4 bytes. */
  1103         -  if( nSize<4 ){
  1104         -    nSize = 4;
  1105         -  }
  1106         -
  1107         -  assert( nSize==debuginfo.nSize );
         1106  +  assert( nSize==debuginfo.nSize || CORRUPT_DB );
  1108   1107     return (u16)nSize;
  1109   1108   }
  1110   1109   
  1111   1110   #ifdef SQLITE_DEBUG
  1112   1111   /* This variation on cellSizePtr() is used inside of assert() statements
  1113   1112   ** only. */
  1114   1113   static u16 cellSize(MemPage *pPage, int iCell){
................................................................................
  1123   1122   ** for the overflow page.
  1124   1123   */
  1125   1124   static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  1126   1125     CellInfo info;
  1127   1126     if( *pRC ) return;
  1128   1127     assert( pCell!=0 );
  1129   1128     btreeParseCellPtr(pPage, pCell, &info);
  1130         -  assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  1131   1129     if( info.iOverflow ){
  1132   1130       Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  1133   1131       ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  1134   1132     }
  1135   1133   }
  1136   1134   #endif
  1137   1135   
................................................................................
  1336   1334   ** Note that even though the freeblock list was checked by btreeInitPage(),
  1337   1335   ** that routine will not detect overlap between cells or freeblocks.  Nor
  1338   1336   ** does it detect cells or freeblocks that encrouch into the reserved bytes
  1339   1337   ** at the end of the page.  So do additional corruption checks inside this
  1340   1338   ** routine and return SQLITE_CORRUPT if any problems are found.
  1341   1339   */
  1342   1340   static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  1343         -  u16 iPtr;                             /* Address of pointer to next freeblock */
         1341  +  u16 iPtr;                             /* Address of ptr to next freeblock */
  1344   1342     u16 iFreeBlk;                         /* Address of the next freeblock */
  1345   1343     u8 hdr;                               /* Page header size.  0 or 100 */
  1346   1344     u8 nFrag = 0;                         /* Reduction in fragmentation */
  1347   1345     u16 iOrigSize = iSize;                /* Original value of iSize */
  1348   1346     u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  1349   1347     u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
  1350   1348     unsigned char *data = pPage->aData;   /* Page content */
................................................................................
  1388   1386         nFrag = iFreeBlk - iEnd;
  1389   1387         if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  1390   1388         iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  1391   1389         iSize = iEnd - iStart;
  1392   1390         iFreeBlk = get2byte(&data[iFreeBlk]);
  1393   1391       }
  1394   1392     
  1395         -    /* If iPtr is another freeblock (that is, if iPtr is not the freelist pointer
  1396         -    ** in the page header) then check to see if iStart should be coalesced 
  1397         -    ** onto the end of iPtr.
         1393  +    /* If iPtr is another freeblock (that is, if iPtr is not the freelist
         1394  +    ** pointer in the page header) then check to see if iStart should be
         1395  +    ** coalesced onto the end of iPtr.
  1398   1396       */
  1399   1397       if( iPtr>hdr+1 ){
  1400   1398         int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  1401   1399         if( iPtrEnd+3>=iStart ){
  1402   1400           if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  1403   1401           nFrag += iStart - iPtrEnd;
  1404   1402           iSize = iEnd - iPtr;
................................................................................
  1444   1442     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  1445   1443     pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
  1446   1444     flagByte &= ~PTF_LEAF;
  1447   1445     pPage->childPtrSize = 4-4*pPage->leaf;
  1448   1446     pBt = pPage->pBt;
  1449   1447     if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  1450   1448       pPage->intKey = 1;
  1451         -    pPage->hasData = pPage->leaf;
         1449  +    pPage->intKeyLeaf = pPage->leaf;
         1450  +    pPage->noPayload = !pPage->leaf;
  1452   1451       pPage->maxLocal = pBt->maxLeaf;
  1453   1452       pPage->minLocal = pBt->minLeaf;
  1454   1453     }else if( flagByte==PTF_ZERODATA ){
  1455   1454       pPage->intKey = 0;
  1456         -    pPage->hasData = 0;
         1455  +    pPage->intKeyLeaf = 0;
         1456  +    pPage->noPayload = 0;
  1457   1457       pPage->maxLocal = pBt->maxLocal;
  1458   1458       pPage->minLocal = pBt->minLocal;
  1459   1459     }else{
  1460   1460       return SQLITE_CORRUPT_BKPT;
  1461   1461     }
  1462   1462     pPage->max1bytePayload = pBt->max1bytePayload;
  1463   1463     return SQLITE_OK;
................................................................................
  2623   2623   **
  2624   2624   ** If there is a transaction in progress, this routine is a no-op.
  2625   2625   */
  2626   2626   static void unlockBtreeIfUnused(BtShared *pBt){
  2627   2627     assert( sqlite3_mutex_held(pBt->mutex) );
  2628   2628     assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  2629   2629     if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  2630         -    assert( pBt->pPage1->aData );
         2630  +    MemPage *pPage1 = pBt->pPage1;
         2631  +    assert( pPage1->aData );
  2631   2632       assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  2632         -    assert( pBt->pPage1->aData );
  2633         -    releasePage(pBt->pPage1);
  2634   2633       pBt->pPage1 = 0;
         2634  +    releasePage(pPage1);
  2635   2635     }
  2636   2636   }
  2637   2637   
  2638   2638   /*
  2639   2639   ** If pBt points to an empty file then convert that empty file
  2640   2640   ** into a new empty database by initializing the first page of
  2641   2641   ** the database.
................................................................................
  3668   3668     assert( p->inTrans>TRANS_NONE );
  3669   3669     assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  3670   3670     assert( pBt->pPage1 && pBt->pPage1->aData );
  3671   3671   
  3672   3672     if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  3673   3673       return SQLITE_READONLY;
  3674   3674     }
         3675  +  if( wrFlag ){
         3676  +    allocateTempSpace(pBt);
         3677  +    if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
         3678  +  }
  3675   3679     if( iTable==1 && btreePagecount(pBt)==0 ){
  3676   3680       assert( wrFlag==0 );
  3677   3681       iTable = 0;
  3678   3682     }
  3679   3683   
  3680   3684     /* Now that no other errors can occur, finish filling in the BtCursor
  3681   3685     ** variables and link the cursor into the BtShared list.  */
................................................................................
  3857   3861   ** Failure is not possible.  This function always returns SQLITE_OK.
  3858   3862   ** It might just as well be a procedure (returning void) but we continue
  3859   3863   ** to return an integer result code for historical reasons.
  3860   3864   */
  3861   3865   int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  3862   3866     assert( cursorHoldsMutex(pCur) );
  3863   3867     assert( pCur->eState==CURSOR_VALID );
         3868  +  assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
  3864   3869     getCellInfo(pCur);
  3865         -  *pSize = pCur->info.nData;
         3870  +  *pSize = pCur->info.nPayload;
  3866   3871     return SQLITE_OK;
  3867   3872   }
  3868   3873   
  3869   3874   /*
  3870   3875   ** Given the page number of an overflow page in the database (parameter
  3871   3876   ** ovfl), this function finds the page number of the next page in the 
  3872   3877   ** linked list of overflow pages. If possible, it uses the auto-vacuum
................................................................................
  4009   4014     u32 offset,          /* Begin reading this far into payload */
  4010   4015     u32 amt,             /* Read this many bytes */
  4011   4016     unsigned char *pBuf, /* Write the bytes into this buffer */ 
  4012   4017     int eOp              /* zero to read. non-zero to write. */
  4013   4018   ){
  4014   4019     unsigned char *aPayload;
  4015   4020     int rc = SQLITE_OK;
  4016         -  u32 nKey;
  4017   4021     int iIdx = 0;
  4018   4022     MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  4019   4023     BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
  4020   4024   #ifdef SQLITE_DIRECT_OVERFLOW_READ
  4021         -  int bEnd;                                   /* True if reading to end of data */
         4025  +  int bEnd;                                 /* True if reading to end of data */
  4022   4026   #endif
  4023   4027   
  4024   4028     assert( pPage );
  4025   4029     assert( pCur->eState==CURSOR_VALID );
  4026   4030     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  4027   4031     assert( cursorHoldsMutex(pCur) );
  4028         -  assert( eOp!=2 || offset==0 );      /* Always start from beginning for eOp==2 */
         4032  +  assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
  4029   4033   
  4030   4034     getCellInfo(pCur);
  4031         -  aPayload = pCur->info.pCell + pCur->info.nHeader;
  4032         -  nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
         4035  +  aPayload = pCur->info.pPayload;
  4033   4036   #ifdef SQLITE_DIRECT_OVERFLOW_READ
  4034         -  bEnd = (offset+amt==nKey+pCur->info.nData);
         4037  +  bEnd = offset+amt==pCur->info.nPayload;
  4035   4038   #endif
         4039  +  assert( offset+amt <= pCur->info.nPayload );
  4036   4040   
  4037         -  if( NEVER(offset+amt > nKey+pCur->info.nData) 
  4038         -   || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  4039         -  ){
         4041  +  if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
  4040   4042       /* Trying to read or write past the end of the data is an error */
  4041   4043       return SQLITE_CORRUPT_BKPT;
  4042   4044     }
  4043   4045   
  4044   4046     /* Check if data must be read/written to/from the btree page itself. */
  4045   4047     if( offset<pCur->info.nLocal ){
  4046   4048       int a = amt;
................................................................................
  4088   4090         }
  4089   4091       }
  4090   4092   
  4091   4093       /* If the overflow page-list cache has been allocated and the
  4092   4094       ** entry for the first required overflow page is valid, skip
  4093   4095       ** directly to it.
  4094   4096       */
  4095         -    if( (pCur->curFlags & BTCF_ValidOvfl)!=0 && pCur->aOverflow[offset/ovflSize] ){
         4097  +    if( (pCur->curFlags & BTCF_ValidOvfl)!=0
         4098  +     && pCur->aOverflow[offset/ovflSize]
         4099  +    ){
  4096   4100         iIdx = (offset/ovflSize);
  4097   4101         nextPage = pCur->aOverflow[iIdx];
  4098   4102         offset = (offset%ovflSize);
  4099   4103       }
  4100   4104   
  4101   4105       for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  4102   4106   
................................................................................
  4266   4270     assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  4267   4271     assert( pCur->eState==CURSOR_VALID );
  4268   4272     assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  4269   4273     assert( cursorHoldsMutex(pCur) );
  4270   4274     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  4271   4275     assert( pCur->info.nSize>0 );
  4272   4276     *pAmt = pCur->info.nLocal;
  4273         -  return (void*)(pCur->info.pCell + pCur->info.nHeader);
         4277  +  return (void*)pCur->info.pPayload;
  4274   4278   }
  4275   4279   
  4276   4280   
  4277   4281   /*
  4278   4282   ** For the entry that cursor pCur is point to, return as
  4279   4283   ** many bytes of the key or data as are available on the local
  4280   4284   ** b-tree page.  Write the number of available bytes into *pAmt.
................................................................................
  4694   4698       assert( biasRight==0 || biasRight==1 );
  4695   4699       idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  4696   4700       pCur->aiIdx[pCur->iPage] = (u16)idx;
  4697   4701       if( xRecordCompare==0 ){
  4698   4702         for(;;){
  4699   4703           i64 nCellKey;
  4700   4704           pCell = findCell(pPage, idx) + pPage->childPtrSize;
  4701         -        if( pPage->hasData ){
         4705  +        if( pPage->intKeyLeaf ){
  4702   4706             while( 0x80 <= *(pCell++) ){
  4703   4707               if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  4704   4708             }
  4705   4709           }
  4706   4710           getVarint(pCell, (u64*)&nCellKey);
  4707   4711           if( nCellKey<intKey ){
  4708   4712             lwr = idx+1;
................................................................................
  4953   4957   ** Step the cursor to the back to the previous entry in the database.  If
  4954   4958   ** successful then set *pRes=0.  If the cursor
  4955   4959   ** was already pointing to the first entry in the database before
  4956   4960   ** this routine was called, then set *pRes=1.
  4957   4961   **
  4958   4962   ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
  4959   4963   ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  4960         -** to the previous cell on the current page.  The (slower) btreePrevious() helper
  4961         -** routine is called when it is necessary to move to a different page or
  4962         -** to restore the cursor.
         4964  +** to the previous cell on the current page.  The (slower) btreePrevious()
         4965  +** helper routine is called when it is necessary to move to a different page
         4966  +** or to restore the cursor.
  4963   4967   **
  4964   4968   ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
  4965   4969   ** will be 1 if the cursor being stepped corresponds to an SQL index and
  4966   4970   ** if this routine could have been skipped if that SQL index had been
  4967   4971   ** a unique index.  Otherwise the caller will have set *pRes to zero.
  4968   4972   ** Zero is the common case. The btree implementation is free to use the
  4969   4973   ** initial *pRes value as a hint to improve performance, but the current
................................................................................
  5283   5287                    *pPgno, closest+1, k, pTrunk->pgno, n-1));
  5284   5288             rc = sqlite3PagerWrite(pTrunk->pDbPage);
  5285   5289             if( rc ) goto end_allocate_page;
  5286   5290             if( closest<k-1 ){
  5287   5291               memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  5288   5292             }
  5289   5293             put4byte(&aData[4], k-1);
  5290         -          noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
         5294  +          noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  5291   5295             rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  5292   5296             if( rc==SQLITE_OK ){
  5293   5297               rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  5294   5298               if( rc!=SQLITE_OK ){
  5295   5299                 releasePage(*ppPage);
  5296   5300               }
  5297   5301             }
................................................................................
  5316   5320       **
  5317   5321       ** Note that the pager will not actually attempt to load or journal 
  5318   5322       ** content for any page that really does lie past the end of the database
  5319   5323       ** file on disk. So the effects of disabling the no-content optimization
  5320   5324       ** here are confined to those pages that lie between the end of the
  5321   5325       ** database image and the end of the database file.
  5322   5326       */
  5323         -    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
         5327  +    int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  5324   5328   
  5325   5329       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  5326   5330       if( rc ) return rc;
  5327   5331       pBt->nPage++;
  5328   5332       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  5329   5333   
  5330   5334   #ifndef SQLITE_OMIT_AUTOVACUUM
................................................................................
  5515   5519   static void freePage(MemPage *pPage, int *pRC){
  5516   5520     if( (*pRC)==SQLITE_OK ){
  5517   5521       *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  5518   5522     }
  5519   5523   }
  5520   5524   
  5521   5525   /*
  5522         -** Free any overflow pages associated with the given Cell.
         5526  +** Free any overflow pages associated with the given Cell.  Write the
         5527  +** local Cell size (the number of bytes on the original page, omitting
         5528  +** overflow) into *pnSize.
  5523   5529   */
  5524         -static int clearCell(MemPage *pPage, unsigned char *pCell){
         5530  +static int clearCell(
         5531  +  MemPage *pPage,          /* The page that contains the Cell */
         5532  +  unsigned char *pCell,    /* First byte of the Cell */
         5533  +  u16 *pnSize              /* Write the size of the Cell here */
         5534  +){
  5525   5535     BtShared *pBt = pPage->pBt;
  5526   5536     CellInfo info;
  5527   5537     Pgno ovflPgno;
  5528   5538     int rc;
  5529   5539     int nOvfl;
  5530   5540     u32 ovflPageSize;
  5531   5541   
  5532   5542     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  5533   5543     btreeParseCellPtr(pPage, pCell, &info);
         5544  +  *pnSize = info.nSize;
  5534   5545     if( info.iOverflow==0 ){
  5535   5546       return SQLITE_OK;  /* No overflow pages. Return without doing anything */
  5536   5547     }
  5537   5548     if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  5538   5549       return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
  5539   5550     }
  5540   5551     ovflPgno = get4byte(&pCell[info.iOverflow]);
................................................................................
  5610   5621     MemPage *pOvfl = 0;
  5611   5622     MemPage *pToRelease = 0;
  5612   5623     unsigned char *pPrior;
  5613   5624     unsigned char *pPayload;
  5614   5625     BtShared *pBt = pPage->pBt;
  5615   5626     Pgno pgnoOvfl = 0;
  5616   5627     int nHeader;
  5617         -  CellInfo info;
  5618   5628   
  5619   5629     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  5620   5630   
  5621   5631     /* pPage is not necessarily writeable since pCell might be auxiliary
  5622   5632     ** buffer space that is separate from the pPage buffer area */
  5623   5633     assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  5624   5634               || sqlite3PagerIswriteable(pPage->pDbPage) );
  5625   5635   
  5626   5636     /* Fill in the header. */
  5627         -  nHeader = 0;
  5628         -  if( !pPage->leaf ){
  5629         -    nHeader += 4;
  5630         -  }
  5631         -  if( pPage->hasData ){
  5632         -    nHeader += putVarint32(&pCell[nHeader], nData+nZero);
         5637  +  nHeader = pPage->childPtrSize;
         5638  +  nPayload = nData + nZero;
         5639  +  if( pPage->intKeyLeaf ){
         5640  +    nHeader += putVarint32(&pCell[nHeader], nPayload);
  5633   5641     }else{
  5634         -    nData = nZero = 0;
         5642  +    assert( nData==0 );
         5643  +    assert( nZero==0 );
  5635   5644     }
  5636   5645     nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  5637         -  btreeParseCellPtr(pPage, pCell, &info);
  5638         -  assert( info.nHeader==nHeader );
  5639         -  assert( info.nKey==nKey );
  5640         -  assert( info.nData==(u32)(nData+nZero) );
  5641   5646     
  5642         -  /* Fill in the payload */
  5643         -  nPayload = nData + nZero;
         5647  +  /* Fill in the payload size */
  5644   5648     if( pPage->intKey ){
  5645   5649       pSrc = pData;
  5646   5650       nSrc = nData;
  5647   5651       nData = 0;
  5648   5652     }else{ 
  5649   5653       if( NEVER(nKey>0x7fffffff || pKey==0) ){
  5650   5654         return SQLITE_CORRUPT_BKPT;
  5651   5655       }
  5652         -    nPayload += (int)nKey;
         5656  +    nPayload = (int)nKey;
  5653   5657       pSrc = pKey;
  5654   5658       nSrc = (int)nKey;
  5655   5659     }
  5656         -  *pnSize = info.nSize;
  5657         -  spaceLeft = info.nLocal;
         5660  +  if( nPayload<=pPage->maxLocal ){
         5661  +    n = nHeader + nPayload;
         5662  +    testcase( n==3 );
         5663  +    testcase( n==4 );
         5664  +    if( n<4 ) n = 4;
         5665  +    *pnSize = n;
         5666  +    spaceLeft = nPayload;
         5667  +    pPrior = pCell;
         5668  +  }else{
         5669  +    int mn = pPage->minLocal;
         5670  +    n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
         5671  +    testcase( n==pPage->maxLocal );
         5672  +    testcase( n==pPage->maxLocal+1 );
         5673  +    if( n > pPage->maxLocal ) n = mn;
         5674  +    spaceLeft = n;
         5675  +    *pnSize = n + nHeader + 4;
         5676  +    pPrior = &pCell[nHeader+n];
         5677  +  }
  5658   5678     pPayload = &pCell[nHeader];
  5659         -  pPrior = &pCell[info.iOverflow];
  5660   5679   
         5680  +  /* At this point variables should be set as follows:
         5681  +  **
         5682  +  **   nPayload           Total payload size in bytes
         5683  +  **   pPayload           Begin writing payload here
         5684  +  **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
         5685  +  **                      that means content must spill into overflow pages.
         5686  +  **   *pnSize            Size of the local cell (not counting overflow pages)
         5687  +  **   pPrior             Where to write the pgno of the first overflow page
         5688  +  **
         5689  +  ** Use a call to btreeParseCellPtr() to verify that the values above
         5690  +  ** were computed correctly.
         5691  +  */
         5692  +#if SQLITE_DEBUG
         5693  +  {
         5694  +    CellInfo info;
         5695  +    btreeParseCellPtr(pPage, pCell, &info);
         5696  +    assert( nHeader=(int)(info.pPayload - pCell) );
         5697  +    assert( info.nKey==nKey );
         5698  +    assert( *pnSize == info.nSize );
         5699  +    assert( spaceLeft == info.nLocal );
         5700  +    assert( pPrior == &pCell[info.iOverflow] );
         5701  +  }
         5702  +#endif
         5703  +
         5704  +  /* Write the payload into the local Cell and any extra into overflow pages */
  5661   5705     while( nPayload>0 ){
  5662   5706       if( spaceLeft==0 ){
  5663   5707   #ifndef SQLITE_OMIT_AUTOVACUUM
  5664   5708         Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  5665   5709         if( pBt->autoVacuum ){
  5666   5710           do{
  5667   5711             pgnoOvfl++;
................................................................................
  6361   6405     ** apCell[] include child pointers.  Either way, all cells in apCell[]
  6362   6406     ** are alike.
  6363   6407     **
  6364   6408     ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
  6365   6409     **       leafData:  1 if pPage holds key+data and pParent holds only keys.
  6366   6410     */
  6367   6411     leafCorrection = apOld[0]->leaf*4;
  6368         -  leafData = apOld[0]->hasData;
         6412  +  leafData = apOld[0]->intKeyLeaf;
  6369   6413     for(i=0; i<nOld; i++){
  6370   6414       int limit;
  6371   6415       
  6372   6416       /* Before doing anything else, take a copy of the i'th original sibling
  6373   6417       ** The rest of this function will use data from the copies rather
  6374   6418       ** that the original pages since the original pages will be in the
  6375   6419       ** process of being overwritten.  */
................................................................................
  6937   6981       }else{
  6938   6982         MemPage * const pParent = pCur->apPage[iPage-1];
  6939   6983         int const iIdx = pCur->aiIdx[iPage-1];
  6940   6984   
  6941   6985         rc = sqlite3PagerWrite(pParent->pDbPage);
  6942   6986         if( rc==SQLITE_OK ){
  6943   6987   #ifndef SQLITE_OMIT_QUICKBALANCE
  6944         -        if( pPage->hasData
         6988  +        if( pPage->intKeyLeaf
  6945   6989            && pPage->nOverflow==1
  6946   6990            && pPage->aiOvfl[0]==pPage->nCell
  6947   6991            && pParent->pgno!=1
  6948   6992            && pParent->nCell==iIdx
  6949   6993           ){
  6950   6994             /* Call balance_quick() to create a new sibling of pPage on which
  6951   6995             ** to store the overflow cell. balance_quick() inserts a new cell
................................................................................
  7056   7100   
  7057   7101     if( pCur->eState==CURSOR_FAULT ){
  7058   7102       assert( pCur->skipNext!=SQLITE_OK );
  7059   7103       return pCur->skipNext;
  7060   7104     }
  7061   7105   
  7062   7106     assert( cursorHoldsMutex(pCur) );
  7063         -  assert( (pCur->curFlags & BTCF_WriteFlag)!=0 && pBt->inTransaction==TRANS_WRITE
         7107  +  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
         7108  +              && pBt->inTransaction==TRANS_WRITE
  7064   7109                 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  7065   7110     assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  7066   7111   
  7067   7112     /* Assert that the caller has been consistent. If this cursor was opened
  7068   7113     ** expecting an index b-tree, then the caller should be inserting blob
  7069   7114     ** keys with no associated data. If the cursor was opened expecting an
  7070   7115     ** intkey table, the caller should be inserting integer keys with a
................................................................................
  7089   7134       /* If this is an insert into a table b-tree, invalidate any incrblob 
  7090   7135       ** cursors open on the row being replaced */
  7091   7136       invalidateIncrblobCursors(p, nKey, 0);
  7092   7137   
  7093   7138       /* If the cursor is currently on the last row and we are appending a
  7094   7139       ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
  7095   7140       ** call */
  7096         -    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0 && pCur->info.nKey==nKey-1 ){
         7141  +    if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
         7142  +      && pCur->info.nKey==nKey-1 ){
  7097   7143         loc = -1;
  7098   7144       }
  7099   7145     }
  7100   7146   
  7101   7147     if( !loc ){
  7102   7148       rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  7103   7149       if( rc ) return rc;
................................................................................
  7108   7154     assert( pPage->intKey || nKey>=0 );
  7109   7155     assert( pPage->leaf || !pPage->intKey );
  7110   7156   
  7111   7157     TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  7112   7158             pCur->pgnoRoot, nKey, nData, pPage->pgno,
  7113   7159             loc==0 ? "overwrite" : "new entry"));
  7114   7160     assert( pPage->isInit );
  7115         -  allocateTempSpace(pBt);
  7116   7161     newCell = pBt->pTmpSpace;
  7117         -  if( newCell==0 ) return SQLITE_NOMEM;
         7162  +  assert( newCell!=0 );
  7118   7163     rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  7119   7164     if( rc ) goto end_insert;
  7120   7165     assert( szNew==cellSizePtr(pPage, newCell) );
  7121   7166     assert( szNew <= MX_CELL_SIZE(pBt) );
  7122   7167     idx = pCur->aiIdx[pCur->iPage];
  7123   7168     if( loc==0 ){
  7124   7169       u16 szOld;
................................................................................
  7127   7172       if( rc ){
  7128   7173         goto end_insert;
  7129   7174       }
  7130   7175       oldCell = findCell(pPage, idx);
  7131   7176       if( !pPage->leaf ){
  7132   7177         memcpy(newCell, oldCell, 4);
  7133   7178       }
  7134         -    szOld = cellSizePtr(pPage, oldCell);
  7135         -    rc = clearCell(pPage, oldCell);
         7179  +    rc = clearCell(pPage, oldCell, &szOld);
  7136   7180       dropCell(pPage, idx, szOld, &rc);
  7137   7181       if( rc ) goto end_insert;
  7138   7182     }else if( loc<0 && pPage->nCell>0 ){
  7139   7183       assert( pPage->leaf );
  7140   7184       idx = ++pCur->aiIdx[pCur->iPage];
  7141   7185     }else{
  7142   7186       assert( pPage->leaf );
................................................................................
  7190   7234     Btree *p = pCur->pBtree;
  7191   7235     BtShared *pBt = p->pBt;              
  7192   7236     int rc;                              /* Return code */
  7193   7237     MemPage *pPage;                      /* Page to delete cell from */
  7194   7238     unsigned char *pCell;                /* Pointer to cell to delete */
  7195   7239     int iCellIdx;                        /* Index of cell to delete */
  7196   7240     int iCellDepth;                      /* Depth of node containing pCell */ 
         7241  +  u16 szCell;                          /* Size of the cell being deleted */
  7197   7242   
  7198   7243     assert( cursorHoldsMutex(pCur) );
  7199   7244     assert( pBt->inTransaction==TRANS_WRITE );
  7200   7245     assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  7201   7246     assert( pCur->curFlags & BTCF_WriteFlag );
  7202   7247     assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  7203   7248     assert( !hasReadConflicts(p, pCur->pgnoRoot) );
................................................................................
  7238   7283     ** invalidate any incrblob cursors open on the row being deleted.  */
  7239   7284     if( pCur->pKeyInfo==0 ){
  7240   7285       invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  7241   7286     }
  7242   7287   
  7243   7288     rc = sqlite3PagerWrite(pPage->pDbPage);
  7244   7289     if( rc ) return rc;
  7245         -  rc = clearCell(pPage, pCell);
  7246         -  dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
         7290  +  rc = clearCell(pPage, pCell, &szCell);
         7291  +  dropCell(pPage, iCellIdx, szCell, &rc);
  7247   7292     if( rc ) return rc;
  7248   7293   
  7249   7294     /* If the cell deleted was not located on a leaf page, then the cursor
  7250   7295     ** is currently pointing to the largest entry in the sub-tree headed
  7251   7296     ** by the child-page of the cell that was just deleted from an internal
  7252   7297     ** node. The cell from the leaf node needs to be moved to the internal
  7253   7298     ** node to replace the deleted cell.  */
................................................................................
  7256   7301       int nCell;
  7257   7302       Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  7258   7303       unsigned char *pTmp;
  7259   7304   
  7260   7305       pCell = findCell(pLeaf, pLeaf->nCell-1);
  7261   7306       nCell = cellSizePtr(pLeaf, pCell);
  7262   7307       assert( MX_CELL_SIZE(pBt) >= nCell );
  7263         -
  7264         -    allocateTempSpace(pBt);
  7265   7308       pTmp = pBt->pTmpSpace;
  7266         -
         7309  +    assert( pTmp!=0 );
  7267   7310       rc = sqlite3PagerWrite(pLeaf->pDbPage);
  7268   7311       insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  7269   7312       dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  7270   7313       if( rc ) return rc;
  7271   7314     }
  7272   7315   
  7273   7316     /* Balance the tree. If the entry deleted was located on a leaf page,
................................................................................
  7471   7514     int *pnChange            /* Add number of Cells freed to this counter */
  7472   7515   ){
  7473   7516     MemPage *pPage;
  7474   7517     int rc;
  7475   7518     unsigned char *pCell;
  7476   7519     int i;
  7477   7520     int hdr;
         7521  +  u16 szCell;
  7478   7522   
  7479   7523     assert( sqlite3_mutex_held(pBt->mutex) );
  7480   7524     if( pgno>btreePagecount(pBt) ){
  7481   7525       return SQLITE_CORRUPT_BKPT;
  7482   7526     }
  7483   7527   
  7484   7528     rc = getAndInitPage(pBt, pgno, &pPage, 0);
................................................................................
  7486   7530     hdr = pPage->hdrOffset;
  7487   7531     for(i=0; i<pPage->nCell; i++){
  7488   7532       pCell = findCell(pPage, i);
  7489   7533       if( !pPage->leaf ){
  7490   7534         rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  7491   7535         if( rc ) goto cleardatabasepage_out;
  7492   7536       }
  7493         -    rc = clearCell(pPage, pCell);
         7537  +    rc = clearCell(pPage, pCell, &szCell);
  7494   7538       if( rc ) goto cleardatabasepage_out;
  7495   7539     }
  7496   7540     if( !pPage->leaf ){
  7497   7541       rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  7498   7542       if( rc ) goto cleardatabasepage_out;
  7499   7543     }else if( pnChange ){
  7500   7544       assert( pPage->intKey );
................................................................................
  7832   7876   
  7833   7877   #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  7834   7878   /*
  7835   7879   ** Append a message to the error message string.
  7836   7880   */
  7837   7881   static void checkAppendMsg(
  7838   7882     IntegrityCk *pCheck,
  7839         -  char *zMsg1,
  7840   7883     const char *zFormat,
  7841   7884     ...
  7842   7885   ){
  7843   7886     va_list ap;
         7887  +  char zBuf[200];
  7844   7888     if( !pCheck->mxErr ) return;
  7845   7889     pCheck->mxErr--;
  7846   7890     pCheck->nErr++;
  7847   7891     va_start(ap, zFormat);
  7848   7892     if( pCheck->errMsg.nChar ){
  7849   7893       sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  7850   7894     }
  7851         -  if( zMsg1 ){
  7852         -    sqlite3StrAccumAppendAll(&pCheck->errMsg, zMsg1);
         7895  +  if( pCheck->zPfx ){
         7896  +    sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
         7897  +    sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
  7853   7898     }
  7854   7899     sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  7855   7900     va_end(ap);
  7856   7901     if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  7857   7902       pCheck->mallocFailed = 1;
  7858   7903     }
  7859   7904   }
................................................................................
  7883   7928   ** Add 1 to the reference count for page iPage.  If this is the second
  7884   7929   ** reference to the page, add an error message to pCheck->zErrMsg.
  7885   7930   ** Return 1 if there are 2 or more references to the page and 0 if
  7886   7931   ** if this is the first reference to the page.
  7887   7932   **
  7888   7933   ** Also check that the page number is in bounds.
  7889   7934   */
  7890         -static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
         7935  +static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  7891   7936     if( iPage==0 ) return 1;
  7892   7937     if( iPage>pCheck->nPage ){
  7893         -    checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
         7938  +    checkAppendMsg(pCheck, "invalid page number %d", iPage);
  7894   7939       return 1;
  7895   7940     }
  7896   7941     if( getPageReferenced(pCheck, iPage) ){
  7897         -    checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
         7942  +    checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  7898   7943       return 1;
  7899   7944     }
  7900   7945     setPageReferenced(pCheck, iPage);
  7901   7946     return 0;
  7902   7947   }
  7903   7948   
  7904   7949   #ifndef SQLITE_OMIT_AUTOVACUUM
................................................................................
  7907   7952   ** page iParent, pointer type ptrType. If not, append an error message
  7908   7953   ** to pCheck.
  7909   7954   */
  7910   7955   static void checkPtrmap(
  7911   7956     IntegrityCk *pCheck,   /* Integrity check context */
  7912   7957     Pgno iChild,           /* Child page number */
  7913   7958     u8 eType,              /* Expected pointer map type */
  7914         -  Pgno iParent,          /* Expected pointer map parent page number */
  7915         -  char *zContext         /* Context description (used for error msg) */
         7959  +  Pgno iParent           /* Expected pointer map parent page number */
  7916   7960   ){
  7917   7961     int rc;
  7918   7962     u8 ePtrmapType;
  7919   7963     Pgno iPtrmapParent;
  7920   7964   
  7921   7965     rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  7922   7966     if( rc!=SQLITE_OK ){
  7923   7967       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  7924         -    checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
         7968  +    checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  7925   7969       return;
  7926   7970     }
  7927   7971   
  7928   7972     if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  7929         -    checkAppendMsg(pCheck, zContext, 
         7973  +    checkAppendMsg(pCheck,
  7930   7974         "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
  7931   7975         iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  7932   7976     }
  7933   7977   }
  7934   7978   #endif
  7935   7979   
  7936   7980   /*
................................................................................
  7937   7981   ** Check the integrity of the freelist or of an overflow page list.
  7938   7982   ** Verify that the number of pages on the list is N.
  7939   7983   */
  7940   7984   static void checkList(
  7941   7985     IntegrityCk *pCheck,  /* Integrity checking context */
  7942   7986     int isFreeList,       /* True for a freelist.  False for overflow page list */
  7943   7987     int iPage,            /* Page number for first page in the list */
  7944         -  int N,                /* Expected number of pages in the list */
  7945         -  char *zContext        /* Context for error messages */
         7988  +  int N                 /* Expected number of pages in the list */
  7946   7989   ){
  7947   7990     int i;
  7948   7991     int expected = N;
  7949   7992     int iFirst = iPage;
  7950   7993     while( N-- > 0 && pCheck->mxErr ){
  7951   7994       DbPage *pOvflPage;
  7952   7995       unsigned char *pOvflData;
  7953   7996       if( iPage<1 ){
  7954         -      checkAppendMsg(pCheck, zContext,
         7997  +      checkAppendMsg(pCheck,
  7955   7998            "%d of %d pages missing from overflow list starting at %d",
  7956   7999             N+1, expected, iFirst);
  7957   8000         break;
  7958   8001       }
  7959         -    if( checkRef(pCheck, iPage, zContext) ) break;
         8002  +    if( checkRef(pCheck, iPage) ) break;
  7960   8003       if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  7961         -      checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
         8004  +      checkAppendMsg(pCheck, "failed to get page %d", iPage);
  7962   8005         break;
  7963   8006       }
  7964   8007       pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  7965   8008       if( isFreeList ){
  7966   8009         int n = get4byte(&pOvflData[4]);
  7967   8010   #ifndef SQLITE_OMIT_AUTOVACUUM
  7968   8011         if( pCheck->pBt->autoVacuum ){
  7969         -        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
         8012  +        checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  7970   8013         }
  7971   8014   #endif
  7972   8015         if( n>(int)pCheck->pBt->usableSize/4-2 ){
  7973         -        checkAppendMsg(pCheck, zContext,
         8016  +        checkAppendMsg(pCheck,
  7974   8017              "freelist leaf count too big on page %d", iPage);
  7975   8018           N--;
  7976   8019         }else{
  7977   8020           for(i=0; i<n; i++){
  7978   8021             Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  7979   8022   #ifndef SQLITE_OMIT_AUTOVACUUM
  7980   8023             if( pCheck->pBt->autoVacuum ){
  7981         -            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
         8024  +            checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  7982   8025             }
  7983   8026   #endif
  7984         -          checkRef(pCheck, iFreePage, zContext);
         8027  +          checkRef(pCheck, iFreePage);
  7985   8028           }
  7986   8029           N -= n;
  7987   8030         }
  7988   8031       }
  7989   8032   #ifndef SQLITE_OMIT_AUTOVACUUM
  7990   8033       else{
  7991   8034         /* If this database supports auto-vacuum and iPage is not the last
  7992   8035         ** page in this overflow list, check that the pointer-map entry for
  7993   8036         ** the following page matches iPage.
  7994   8037         */
  7995   8038         if( pCheck->pBt->autoVacuum && N>0 ){
  7996   8039           i = get4byte(pOvflData);
  7997         -        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
         8040  +        checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  7998   8041         }
  7999   8042       }
  8000   8043   #endif
  8001   8044       iPage = get4byte(pOvflData);
  8002   8045       sqlite3PagerUnref(pOvflPage);
  8003   8046     }
  8004   8047   }
................................................................................
  8022   8065   **      7.  Verify that the depth of all children is the same.
  8023   8066   **      8.  Make sure this page is at least 33% full or else it is
  8024   8067   **          the root of the tree.
  8025   8068   */
  8026   8069   static int checkTreePage(
  8027   8070     IntegrityCk *pCheck,  /* Context for the sanity check */
  8028   8071     int iPage,            /* Page number of the page to check */
  8029         -  char *zParentContext, /* Parent context */
  8030   8072     i64 *pnParentMinKey, 
  8031   8073     i64 *pnParentMaxKey
  8032   8074   ){
  8033   8075     MemPage *pPage;
  8034   8076     int i, rc, depth, d2, pgno, cnt;
  8035   8077     int hdr, cellStart;
  8036   8078     int nCell;
  8037   8079     u8 *data;
  8038   8080     BtShared *pBt;
  8039   8081     int usableSize;
  8040         -  char zContext[100];
  8041   8082     char *hit = 0;
  8042   8083     i64 nMinKey = 0;
  8043   8084     i64 nMaxKey = 0;
  8044         -
  8045         -  sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
         8085  +  const char *saved_zPfx = pCheck->zPfx;
         8086  +  int saved_v1 = pCheck->v1;
         8087  +  int saved_v2 = pCheck->v2;
  8046   8088   
  8047   8089     /* Check that the page exists
  8048   8090     */
  8049   8091     pBt = pCheck->pBt;
  8050   8092     usableSize = pBt->usableSize;
  8051   8093     if( iPage==0 ) return 0;
  8052         -  if( checkRef(pCheck, iPage, zParentContext) ) return 0;
         8094  +  if( checkRef(pCheck, iPage) ) return 0;
         8095  +  pCheck->zPfx = "Page %d: ";
         8096  +  pCheck->v1 = iPage;
  8053   8097     if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  8054         -    checkAppendMsg(pCheck, zContext,
         8098  +    checkAppendMsg(pCheck,
  8055   8099          "unable to get the page. error code=%d", rc);
  8056         -    return 0;
         8100  +    depth = -1;
         8101  +    goto end_of_check;
  8057   8102     }
  8058   8103   
  8059   8104     /* Clear MemPage.isInit to make sure the corruption detection code in
  8060   8105     ** btreeInitPage() is executed.  */
  8061   8106     pPage->isInit = 0;
  8062   8107     if( (rc = btreeInitPage(pPage))!=0 ){
  8063   8108       assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
  8064         -    checkAppendMsg(pCheck, zContext, 
         8109  +    checkAppendMsg(pCheck,
  8065   8110                      "btreeInitPage() returns error code %d", rc);
  8066   8111       releasePage(pPage);
  8067         -    return 0;
         8112  +    depth = -1;
         8113  +    goto end_of_check;
  8068   8114     }
  8069   8115   
  8070   8116     /* Check out all the cells.
  8071   8117     */
  8072   8118     depth = 0;
  8073   8119     for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  8074   8120       u8 *pCell;
  8075   8121       u32 sz;
  8076   8122       CellInfo info;
  8077   8123   
  8078   8124       /* Check payload overflow pages
  8079   8125       */
  8080         -    sqlite3_snprintf(sizeof(zContext), zContext,
  8081         -             "On tree page %d cell %d: ", iPage, i);
         8126  +    pCheck->zPfx = "On tree page %d cell %d: ";
         8127  +    pCheck->v1 = iPage;
         8128  +    pCheck->v2 = i;
  8082   8129       pCell = findCell(pPage,i);
  8083   8130       btreeParseCellPtr(pPage, pCell, &info);
  8084         -    sz = info.nData;
  8085         -    if( !pPage->intKey ) sz += (int)info.nKey;
         8131  +    sz = info.nPayload;
  8086   8132       /* For intKey pages, check that the keys are in order.
  8087   8133       */
  8088         -    else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  8089         -    else{
  8090         -      if( info.nKey <= nMaxKey ){
  8091         -        checkAppendMsg(pCheck, zContext, 
  8092         -            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
         8134  +    if( pPage->intKey ){
         8135  +      if( i==0 ){
         8136  +        nMinKey = nMaxKey = info.nKey;
         8137  +      }else if( info.nKey <= nMaxKey ){
         8138  +        checkAppendMsg(pCheck,
         8139  +           "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  8093   8140         }
  8094   8141         nMaxKey = info.nKey;
  8095   8142       }
  8096         -    assert( sz==info.nPayload );
  8097   8143       if( (sz>info.nLocal) 
  8098   8144        && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  8099   8145       ){
  8100   8146         int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  8101   8147         Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  8102   8148   #ifndef SQLITE_OMIT_AUTOVACUUM
  8103   8149         if( pBt->autoVacuum ){
  8104         -        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
         8150  +        checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  8105   8151         }
  8106   8152   #endif
  8107         -      checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
         8153  +      checkList(pCheck, 0, pgnoOvfl, nPage);
  8108   8154       }
  8109   8155   
  8110   8156       /* Check sanity of left child page.
  8111   8157       */
  8112   8158       if( !pPage->leaf ){
  8113   8159         pgno = get4byte(pCell);
  8114   8160   #ifndef SQLITE_OMIT_AUTOVACUUM
  8115   8161         if( pBt->autoVacuum ){
  8116         -        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
         8162  +        checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  8117   8163         }
  8118   8164   #endif
  8119         -      d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
         8165  +      d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
  8120   8166         if( i>0 && d2!=depth ){
  8121         -        checkAppendMsg(pCheck, zContext, "Child page depth differs");
         8167  +        checkAppendMsg(pCheck, "Child page depth differs");
  8122   8168         }
  8123   8169         depth = d2;
  8124   8170       }
  8125   8171     }
  8126   8172   
  8127   8173     if( !pPage->leaf ){
  8128   8174       pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  8129         -    sqlite3_snprintf(sizeof(zContext), zContext, 
  8130         -                     "On page %d at right child: ", iPage);
         8175  +    pCheck->zPfx = "On page %d at right child: ";
         8176  +    pCheck->v1 = iPage;
  8131   8177   #ifndef SQLITE_OMIT_AUTOVACUUM
  8132   8178       if( pBt->autoVacuum ){
  8133         -      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
         8179  +      checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  8134   8180       }
  8135   8181   #endif
  8136         -    checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
         8182  +    checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
  8137   8183     }
  8138   8184    
  8139   8185     /* For intKey leaf pages, check that the min/max keys are in order
  8140   8186     ** with any left/parent/right pages.
  8141   8187     */
         8188  +  pCheck->zPfx = "Page %d: ";
         8189  +  pCheck->v1 = iPage;
  8142   8190     if( pPage->leaf && pPage->intKey ){
  8143   8191       /* if we are a left child page */
  8144   8192       if( pnParentMinKey ){
  8145   8193         /* if we are the left most child page */
  8146   8194         if( !pnParentMaxKey ){
  8147   8195           if( nMaxKey > *pnParentMinKey ){
  8148         -          checkAppendMsg(pCheck, zContext, 
         8196  +          checkAppendMsg(pCheck,
  8149   8197                 "Rowid %lld out of order (max larger than parent min of %lld)",
  8150   8198                 nMaxKey, *pnParentMinKey);
  8151   8199           }
  8152   8200         }else{
  8153   8201           if( nMinKey <= *pnParentMinKey ){
  8154         -          checkAppendMsg(pCheck, zContext, 
         8202  +          checkAppendMsg(pCheck,
  8155   8203                 "Rowid %lld out of order (min less than parent min of %lld)",
  8156   8204                 nMinKey, *pnParentMinKey);
  8157   8205           }
  8158   8206           if( nMaxKey > *pnParentMaxKey ){
  8159         -          checkAppendMsg(pCheck, zContext, 
         8207  +          checkAppendMsg(pCheck,
  8160   8208                 "Rowid %lld out of order (max larger than parent max of %lld)",
  8161   8209                 nMaxKey, *pnParentMaxKey);
  8162   8210           }
  8163   8211           *pnParentMinKey = nMaxKey;
  8164   8212         }
  8165   8213       /* else if we're a right child page */
  8166   8214       } else if( pnParentMaxKey ){
  8167   8215         if( nMinKey <= *pnParentMaxKey ){
  8168         -        checkAppendMsg(pCheck, zContext, 
         8216  +        checkAppendMsg(pCheck,
  8169   8217               "Rowid %lld out of order (min less than parent max of %lld)",
  8170   8218               nMinKey, *pnParentMaxKey);
  8171   8219         }
  8172   8220       }
  8173   8221     }
  8174   8222   
  8175   8223     /* Check for complete coverage of the page
  8176   8224     */
  8177   8225     data = pPage->aData;
  8178   8226     hdr = pPage->hdrOffset;
  8179   8227     hit = sqlite3PageMalloc( pBt->pageSize );
         8228  +  pCheck->zPfx = 0;
  8180   8229     if( hit==0 ){
  8181   8230       pCheck->mallocFailed = 1;
  8182   8231     }else{
  8183   8232       int contentOffset = get2byteNotZero(&data[hdr+5]);
  8184   8233       assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
  8185   8234       memset(hit+contentOffset, 0, usableSize-contentOffset);
  8186   8235       memset(hit, 1, contentOffset);
................................................................................
  8190   8239         int pc = get2byte(&data[cellStart+i*2]);
  8191   8240         u32 size = 65536;
  8192   8241         int j;
  8193   8242         if( pc<=usableSize-4 ){
  8194   8243           size = cellSizePtr(pPage, &data[pc]);
  8195   8244         }
  8196   8245         if( (int)(pc+size-1)>=usableSize ){
  8197         -        checkAppendMsg(pCheck, 0, 
         8246  +        pCheck->zPfx = 0;
         8247  +        checkAppendMsg(pCheck,
  8198   8248               "Corruption detected in cell %d on page %d",i,iPage);
  8199   8249         }else{
  8200   8250           for(j=pc+size-1; j>=pc; j--) hit[j]++;
  8201   8251         }
  8202   8252       }
  8203   8253       i = get2byte(&data[hdr+1]);
  8204   8254       while( i>0 ){
................................................................................
  8212   8262         assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
  8213   8263         i = j;
  8214   8264       }
  8215   8265       for(i=cnt=0; i<usableSize; i++){
  8216   8266         if( hit[i]==0 ){
  8217   8267           cnt++;
  8218   8268         }else if( hit[i]>1 ){
  8219         -        checkAppendMsg(pCheck, 0,
         8269  +        checkAppendMsg(pCheck,
  8220   8270             "Multiple uses for byte %d of page %d", i, iPage);
  8221   8271           break;
  8222   8272         }
  8223   8273       }
  8224   8274       if( cnt!=data[hdr+7] ){
  8225         -      checkAppendMsg(pCheck, 0, 
         8275  +      checkAppendMsg(pCheck,
  8226   8276             "Fragmentation of %d bytes reported as %d on page %d",
  8227   8277             cnt, data[hdr+7], iPage);
  8228   8278       }
  8229   8279     }
  8230   8280     sqlite3PageFree(hit);
  8231   8281     releasePage(pPage);
         8282  +
         8283  +end_of_check:
         8284  +  pCheck->zPfx = saved_zPfx;
         8285  +  pCheck->v1 = saved_v1;
         8286  +  pCheck->v2 = saved_v2;
  8232   8287     return depth+1;
  8233   8288   }
  8234   8289   #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  8235   8290   
  8236   8291   #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  8237   8292   /*
  8238   8293   ** This routine does a complete check of the given BTree file.  aRoot[] is
................................................................................
  8265   8320     nRef = sqlite3PagerRefcount(pBt->pPager);
  8266   8321     sCheck.pBt = pBt;
  8267   8322     sCheck.pPager = pBt->pPager;
  8268   8323     sCheck.nPage = btreePagecount(sCheck.pBt);
  8269   8324     sCheck.mxErr = mxErr;
  8270   8325     sCheck.nErr = 0;
  8271   8326     sCheck.mallocFailed = 0;
         8327  +  sCheck.zPfx = 0;
         8328  +  sCheck.v1 = 0;
         8329  +  sCheck.v2 = 0;
  8272   8330     *pnErr = 0;
  8273   8331     if( sCheck.nPage==0 ){
  8274   8332       sqlite3BtreeLeave(p);
  8275   8333       return 0;
  8276   8334     }
  8277   8335   
  8278   8336     sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
................................................................................
  8284   8342     i = PENDING_BYTE_PAGE(pBt);
  8285   8343     if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  8286   8344     sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  8287   8345     sCheck.errMsg.useMalloc = 2;
  8288   8346   
  8289   8347     /* Check the integrity of the freelist
  8290   8348     */
         8349  +  sCheck.zPfx = "Main freelist: ";
  8291   8350     checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  8292         -            get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
         8351  +            get4byte(&pBt->pPage1->aData[36]));
         8352  +  sCheck.zPfx = 0;
  8293   8353   
  8294   8354     /* Check all the tables.
  8295   8355     */
  8296   8356     for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  8297   8357       if( aRoot[i]==0 ) continue;
  8298   8358   #ifndef SQLITE_OMIT_AUTOVACUUM
  8299   8359       if( pBt->autoVacuum && aRoot[i]>1 ){
  8300         -      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
         8360  +      checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  8301   8361       }
  8302   8362   #endif
  8303         -    checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
         8363  +    sCheck.zPfx = "List of tree roots: ";
         8364  +    checkTreePage(&sCheck, aRoot[i], NULL, NULL);
         8365  +    sCheck.zPfx = 0;
  8304   8366     }
  8305   8367   
  8306   8368     /* Make sure every page in the file is referenced
  8307   8369     */
  8308   8370     for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  8309   8371   #ifdef SQLITE_OMIT_AUTOVACUUM
  8310   8372       if( getPageReferenced(&sCheck, i)==0 ){
  8311         -      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
         8373  +      checkAppendMsg(&sCheck, "Page %d is never used", i);
  8312   8374       }
  8313   8375   #else
  8314   8376       /* If the database supports auto-vacuum, make sure no tables contain
  8315   8377       ** references to pointer-map pages.
  8316   8378       */
  8317   8379       if( getPageReferenced(&sCheck, i)==0 && 
  8318   8380          (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  8319         -      checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
         8381  +      checkAppendMsg(&sCheck, "Page %d is never used", i);
  8320   8382       }
  8321   8383       if( getPageReferenced(&sCheck, i)!=0 && 
  8322   8384          (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  8323         -      checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
         8385  +      checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  8324   8386       }
  8325   8387   #endif
  8326   8388     }
  8327   8389   
  8328   8390     /* Make sure this analysis did not leave any unref() pages.
  8329   8391     ** This is an internal consistency check; an integrity check
  8330   8392     ** of the integrity check.
  8331   8393     */
  8332   8394     if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  8333         -    checkAppendMsg(&sCheck, 0, 
         8395  +    checkAppendMsg(&sCheck,
  8334   8396         "Outstanding page count goes from %d to %d during this analysis",
  8335   8397         nRef, sqlite3PagerRefcount(pBt->pPager)
  8336   8398       );
  8337   8399     }
  8338   8400   
  8339   8401     /* Clean  up and report errors.
  8340   8402     */
................................................................................
  8522   8584       return SQLITE_ABORT;
  8523   8585     }
  8524   8586   
  8525   8587     /* Save the positions of all other cursors open on this table. This is
  8526   8588     ** required in case any of them are holding references to an xFetch
  8527   8589     ** version of the b-tree page modified by the accessPayload call below.
  8528   8590     **
  8529         -  ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
         8591  +  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  8530   8592     ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  8531   8593     ** saveAllCursors can only return SQLITE_OK.
  8532   8594     */
  8533   8595     VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  8534   8596     assert( rc==SQLITE_OK );
  8535   8597   
  8536   8598     /* Check some assumptions: 

Changes to src/btreeInt.h.

   269    269   **
   270    270   ** Access to all fields of this structure is controlled by the mutex
   271    271   ** stored in MemPage.pBt->mutex.
   272    272   */
   273    273   struct MemPage {
   274    274     u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
   275    275     u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
   276         -  u8 intKey;           /* True if intkey flag is set */
   277         -  u8 leaf;             /* True if leaf flag is set */
   278         -  u8 hasData;          /* True if this page stores data */
          276  +  u8 intKey;           /* True if table b-trees.  False for index b-trees */
          277  +  u8 intKeyLeaf;       /* True if the leaf of an intKey table */
          278  +  u8 noPayload;        /* True if internal intKey page (thus w/o data) */
          279  +  u8 leaf;             /* True if a leaf page */
   279    280     u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
   280    281     u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
   281    282     u8 max1bytePayload;  /* min(maxLocal,127) */
   282    283     u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
   283    284     u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
   284    285     u16 cellOffset;      /* Index in aData of first cell pointer */
   285    286     u16 nFree;           /* Number of free bytes on the page */
................................................................................
   452    453   /*
   453    454   ** An instance of the following structure is used to hold information
   454    455   ** about a cell.  The parseCellPtr() function fills in this structure
   455    456   ** based on information extract from the raw disk page.
   456    457   */
   457    458   typedef struct CellInfo CellInfo;
   458    459   struct CellInfo {
   459         -  i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
   460         -  u8 *pCell;     /* Pointer to the start of cell content */
   461         -  u32 nData;     /* Number of bytes of data */
   462         -  u32 nPayload;  /* Total amount of payload */
   463         -  u16 nHeader;   /* Size of the cell content header in bytes */
   464         -  u16 nLocal;    /* Amount of payload held locally */
          460  +  i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
          461  +  u8 *pPayload;  /* Pointer to the start of payload */
          462  +  u32 nPayload;  /* Bytes of payload */
          463  +  u16 nLocal;    /* Amount of payload held locally, not on overflow */
   465    464     u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
   466    465     u16 nSize;     /* Size of the cell content on the main b-tree page */
   467    466   };
   468    467   
   469    468   /*
   470    469   ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
   471    470   ** this will be declared corrupt. This value is calculated based on a
................................................................................
   654    653     BtShared *pBt;    /* The tree being checked out */
   655    654     Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
   656    655     u8 *aPgRef;       /* 1 bit per page in the db (see above) */
   657    656     Pgno nPage;       /* Number of pages in the database */
   658    657     int mxErr;        /* Stop accumulating errors when this reaches zero */
   659    658     int nErr;         /* Number of messages written to zErrMsg so far */
   660    659     int mallocFailed; /* A memory allocation error has occurred */
          660  +  const char *zPfx; /* Error message prefix */
          661  +  int v1, v2;       /* Values for up to two %d fields in zPfx */
   661    662     StrAccum errMsg;  /* Accumulate the error message text here */
   662    663   };
   663    664   
   664    665   /*
   665    666   ** Routines to read or write a two- and four-byte big-endian integer values.
   666    667   */
   667    668   #define get2byte(x)   ((x)[0]<<8 | (x)[1])
   668    669   #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
   669    670   #define get4byte sqlite3Get4byte
   670    671   #define put4byte sqlite3Put4byte

Changes to src/build.c.

  1232   1232   void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  1233   1233     Table *p;
  1234   1234     Column *pCol;
  1235   1235     sqlite3 *db = pParse->db;
  1236   1236     p = pParse->pNewTable;
  1237   1237     if( p!=0 ){
  1238   1238       pCol = &(p->aCol[p->nCol-1]);
  1239         -    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
         1239  +    if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  1240   1240         sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  1241   1241             pCol->zName);
  1242   1242       }else{
  1243   1243         /* A copy of pExpr is used instead of the original, as pExpr contains
  1244   1244         ** tokens that point to volatile memory. The 'span' of the expression
  1245   1245         ** is required by pragma table_info.
  1246   1246         */

Changes to src/ctime.c.

   391    391     if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
   392    392     n = sqlite3Strlen30(zOptName);
   393    393   
   394    394     /* Since ArraySize(azCompileOpt) is normally in single digits, a
   395    395     ** linear search is adequate.  No need for a binary search. */
   396    396     for(i=0; i<ArraySize(azCompileOpt); i++){
   397    397       if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
   398         -     && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
          398  +     && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
   399    399       ){
   400    400         return 1;
   401    401       }
   402    402     }
   403    403     return 0;
   404    404   }
   405    405   

Changes to src/expr.c.

  1208   1208     sqlite3DbFree(db, pList->a);
  1209   1209     sqlite3DbFree(db, pList);
  1210   1210   }
  1211   1211   
  1212   1212   /*
  1213   1213   ** These routines are Walker callbacks.  Walker.u.pi is a pointer
  1214   1214   ** to an integer.  These routines are checking an expression to see
  1215         -** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
         1215  +** if it is a constant.  Set *Walker.u.i to 0 if the expression is
  1216   1216   ** not constant.
  1217   1217   **
  1218   1218   ** These callback routines are used to implement the following:
  1219   1219   **
  1220         -**     sqlite3ExprIsConstant()
  1221         -**     sqlite3ExprIsConstantNotJoin()
  1222         -**     sqlite3ExprIsConstantOrFunction()
         1220  +**     sqlite3ExprIsConstant()                  pWalker->u.i==1
         1221  +**     sqlite3ExprIsConstantNotJoin()           pWalker->u.i==2
         1222  +**     sqlite3ExprIsConstantOrFunction()        pWalker->u.i==3 or 4
  1223   1223   **
         1224  +** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
         1225  +** in a CREATE TABLE statement.  The Walker.u.i value is 4 when parsing
         1226  +** an existing schema and 3 when processing a new statement.  A bound
         1227  +** parameter raises an error for new statements, but is silently converted
         1228  +** to NULL for existing schemas.  This allows sqlite_master tables that 
         1229  +** contain a bound parameter because they were generated by older versions
         1230  +** of SQLite to be parsed by newer versions of SQLite without raising a
         1231  +** malformed schema error.
  1224   1232   */
  1225   1233   static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  1226   1234   
  1227         -  /* If pWalker->u.i is 3 then any term of the expression that comes from
         1235  +  /* If pWalker->u.i is 2 then any term of the expression that comes from
  1228   1236     ** the ON or USING clauses of a join disqualifies the expression
  1229   1237     ** from being considered constant. */
  1230         -  if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
         1238  +  if( pWalker->u.i==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  1231   1239       pWalker->u.i = 0;
  1232   1240       return WRC_Abort;
  1233   1241     }
  1234   1242   
  1235   1243     switch( pExpr->op ){
  1236   1244       /* Consider functions to be constant if all their arguments are constant
  1237         -    ** and either pWalker->u.i==2 or the function as the SQLITE_FUNC_CONST
         1245  +    ** and either pWalker->u.i==3 or 4 or the function as the SQLITE_FUNC_CONST
  1238   1246       ** flag. */
  1239   1247       case TK_FUNCTION:
  1240         -      if( pWalker->u.i==2 || ExprHasProperty(pExpr,EP_Constant) ){
         1248  +      if( pWalker->u.i>=3 || ExprHasProperty(pExpr,EP_Constant) ){
  1241   1249           return WRC_Continue;
  1242   1250         }
  1243   1251         /* Fall through */
  1244   1252       case TK_ID:
  1245   1253       case TK_COLUMN:
  1246   1254       case TK_AGG_FUNCTION:
  1247   1255       case TK_AGG_COLUMN:
  1248   1256         testcase( pExpr->op==TK_ID );
  1249   1257         testcase( pExpr->op==TK_COLUMN );
  1250   1258         testcase( pExpr->op==TK_AGG_FUNCTION );
  1251   1259         testcase( pExpr->op==TK_AGG_COLUMN );
  1252   1260         pWalker->u.i = 0;
  1253   1261         return WRC_Abort;
         1262  +    case TK_VARIABLE:
         1263  +      if( pWalker->u.i==4 ){
         1264  +        /* Silently convert bound parameters that appear inside of CREATE
         1265  +        ** statements into a NULL when parsing the CREATE statement text out
         1266  +        ** of the sqlite_master table */
         1267  +        pExpr->op = TK_NULL;
         1268  +      }else if( pWalker->u.i==3 ){
         1269  +        /* A bound parameter in a CREATE statement that originates from
         1270  +        ** sqlite3_prepare() causes an error */
         1271  +        pWalker->u.i = 0;
         1272  +        return WRC_Abort;
         1273  +      }
         1274  +      /* Fall through */
  1254   1275       default:
  1255   1276         testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  1256   1277         testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  1257   1278         return WRC_Continue;
  1258   1279     }
  1259   1280   }
  1260   1281   static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
................................................................................
  1287   1308   /*
  1288   1309   ** Walk an expression tree.  Return 1 if the expression is constant
  1289   1310   ** that does no originate from the ON or USING clauses of a join.
  1290   1311   ** Return 0 if it involves variables or function calls or terms from
  1291   1312   ** an ON or USING clause.
  1292   1313   */
  1293   1314   int sqlite3ExprIsConstantNotJoin(Expr *p){
  1294         -  return exprIsConst(p, 3);
         1315  +  return exprIsConst(p, 2);
  1295   1316   }
  1296   1317   
  1297   1318   /*
  1298   1319   ** Walk an expression tree.  Return 1 if the expression is constant
  1299   1320   ** or a function call with constant arguments.  Return and 0 if there
  1300   1321   ** are any variables.
  1301   1322   **
  1302   1323   ** For the purposes of this function, a double-quoted string (ex: "abc")
  1303   1324   ** is considered a variable but a single-quoted string (ex: 'abc') is
  1304   1325   ** a constant.
  1305   1326   */
  1306         -int sqlite3ExprIsConstantOrFunction(Expr *p){
  1307         -  return exprIsConst(p, 2);
         1327  +int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
         1328  +  assert( isInit==0 || isInit==1 );
         1329  +  return exprIsConst(p, 3+isInit);
  1308   1330   }
  1309   1331   
  1310   1332   /*
  1311   1333   ** If the expression p codes a constant integer that is small enough
  1312   1334   ** to fit in a 32-bit integer, return 1 and put the value of the integer
  1313   1335   ** in *pValue.  If the expression is not an integer or if it is too big
  1314   1336   ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.

Changes to src/func.c.

    18     18   #include <assert.h>
    19     19   #include "vdbeInt.h"
    20     20   
    21     21   /*
    22     22   ** Return the collating function associated with a function.
    23     23   */
    24     24   static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
    25         -  return context->pColl;
           25  +  VdbeOp *pOp = &context->pVdbe->aOp[context->iOp-1];
           26  +  assert( pOp->opcode==OP_CollSeq );
           27  +  assert( pOp->p4type==P4_COLLSEQ );
           28  +  return pOp->p4.pColl;
    26     29   }
    27     30   
    28     31   /*
    29     32   ** Indicate that the accumulator load should be skipped on this
    30     33   ** iteration of the aggregate loop.
    31     34   */
    32     35   static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
................................................................................
   563    566   /*
   564    567   ** For LIKE and GLOB matching on EBCDIC machines, assume that every
   565    568   ** character is exactly one byte in size.  Also, all characters are
   566    569   ** able to participate in upper-case-to-lower-case mappings in EBCDIC
   567    570   ** whereas only characters less than 0x80 do in ASCII.
   568    571   */
   569    572   #if defined(SQLITE_EBCDIC)
   570         -# define sqlite3Utf8Read(A)    (*((*A)++))
   571         -# define GlobUpperToLower(A)   A = sqlite3UpperToLower[A]
          573  +# define sqlite3Utf8Read(A)        (*((*A)++))
          574  +# define GlobUpperToLower(A)       A = sqlite3UpperToLower[A]
          575  +# define GlobUpperToLowerAscii(A)  A = sqlite3UpperToLower[A]
   572    576   #else
   573         -# define GlobUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
          577  +# define GlobUpperToLower(A)       if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
          578  +# define GlobUpperToLowerAscii(A)  A = sqlite3UpperToLower[A]
   574    579   #endif
   575    580   
   576    581   static const struct compareInfo globInfo = { '*', '?', '[', 0 };
   577    582   /* The correct SQL-92 behavior is for the LIKE operator to ignore
   578    583   ** case.  Thus  'a' LIKE 'A' would be true. */
   579    584   static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
   580    585   /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
   581    586   ** is case sensitive causing 'a' LIKE 'A' to be false */
   582    587   static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
   583    588   
   584    589   /*
   585    590   ** Compare two UTF-8 strings for equality where the first string can
   586         -** potentially be a "glob" expression.  Return true (1) if they
          591  +** potentially be a "glob" or "like" expression.  Return true (1) if they
   587    592   ** are the same and false (0) if they are different.
   588    593   **
   589    594   ** Globbing rules:
   590    595   **
   591    596   **      '*'       Matches any sequence of zero or more characters.
   592    597   **
   593    598   **      '?'       Matches exactly one character.
................................................................................
   599    604   **
   600    605   ** With the [...] and [^...] matching, a ']' character can be included
   601    606   ** in the list by making it the first character after '[' or '^'.  A
   602    607   ** range of characters can be specified using '-'.  Example:
   603    608   ** "[a-z]" matches any single lower-case letter.  To match a '-', make
   604    609   ** it the last character in the list.
   605    610   **
   606         -** This routine is usually quick, but can be N**2 in the worst case.
          611  +** Like matching rules:
          612  +** 
          613  +**      '%'       Matches any sequence of zero or more characters
          614  +**
          615  +***     '_'       Matches any one character
          616  +**
          617  +**      Ec        Where E is the "esc" character and c is any other
          618  +**                character, including '%', '_', and esc, match exactly c.
   607    619   **
   608         -** Hints: to match '*' or '?', put them in "[]".  Like this:
          620  +** The comments through this routine usually assume glob matching.
   609    621   **
   610         -**         abc[*]xyz        Matches "abc*xyz" only
          622  +** This routine is usually quick, but can be N**2 in the worst case.
   611    623   */
   612    624   static int patternCompare(
   613    625     const u8 *zPattern,              /* The glob pattern */
   614    626     const u8 *zString,               /* The string to compare against the glob */
   615    627     const struct compareInfo *pInfo, /* Information about how to do the compare */
   616    628     u32 esc                          /* The escape character */
   617    629   ){
   618         -  u32 c, c2;
   619         -  int invert;
   620         -  int seen;
   621         -  u8 matchOne = pInfo->matchOne;
   622         -  u8 matchAll = pInfo->matchAll;
   623         -  u8 matchSet = pInfo->matchSet;
   624         -  u8 noCase = pInfo->noCase; 
   625         -  int prevEscape = 0;     /* True if the previous character was 'escape' */
          630  +  u32 c, c2;                       /* Next pattern and input string chars */
          631  +  u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
          632  +  u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
          633  +  u32 matchOther;                  /* "[" or the escape character */
          634  +  u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
          635  +  const u8 *zEscaped = 0;          /* One past the last escaped input char */
          636  +  
          637  +  /* The GLOB operator does not have an ESCAPE clause.  And LIKE does not
          638  +  ** have the matchSet operator.  So we either have to look for one or
          639  +  ** the other, never both.  Hence the single variable matchOther is used
          640  +  ** to store the one we have to look for.
          641  +  */
          642  +  matchOther = esc ? esc : pInfo->matchSet;
   626    643   
   627    644     while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
   628         -    if( c==matchAll && !prevEscape ){
          645  +    if( c==matchAll ){  /* Match "*" */
          646  +      /* Skip over multiple "*" characters in the pattern.  If there
          647  +      ** are also "?" characters, skip those as well, but consume a
          648  +      ** single character of the input string for each "?" skipped */
   629    649         while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
   630    650                  || c == matchOne ){
   631    651           if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
   632    652             return 0;
   633    653           }
   634    654         }
   635    655         if( c==0 ){
   636         -        return 1;
   637         -      }else if( c==esc ){
   638         -        c = sqlite3Utf8Read(&zPattern);
   639         -        if( c==0 ){
   640         -          return 0;
   641         -        }
   642         -      }else if( c==matchSet ){
   643         -        assert( esc==0 );         /* This is GLOB, not LIKE */
   644         -        assert( matchSet<0x80 );  /* '[' is a single-byte character */
   645         -        while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
   646         -          SQLITE_SKIP_UTF8(zString);
   647         -        }
   648         -        return *zString!=0;
   649         -      }
   650         -      while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
          656  +        return 1;   /* "*" at the end of the pattern matches */
          657  +      }else if( c==matchOther ){
          658  +        if( esc ){
          659  +          c = sqlite3Utf8Read(&zPattern);
          660  +          if( c==0 ) return 0;
          661  +        }else{
          662  +          /* "[...]" immediately follows the "*".  We have to do a slow
          663  +          ** recursive search in this case, but it is an unusual case. */
          664  +          assert( matchOther<0x80 );  /* '[' is a single-byte character */
          665  +          while( *zString
          666  +                 && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
          667  +            SQLITE_SKIP_UTF8(zString);
          668  +          }
          669  +          return *zString!=0;
          670  +        }
          671  +      }
          672  +
          673  +      /* At this point variable c contains the first character of the
          674  +      ** pattern string past the "*".  Search in the input string for the
          675  +      ** first matching character and recursively contine the match from
          676  +      ** that point.
          677  +      **
          678  +      ** For a case-insensitive search, set variable cx to be the same as
          679  +      ** c but in the other case and search the input string for either
          680  +      ** c or cx.
          681  +      */
          682  +      if( c<=0x80 ){
          683  +        u32 cx;
   651    684           if( noCase ){
   652         -          GlobUpperToLower(c2);
   653         -          GlobUpperToLower(c);
   654         -          while( c2 != 0 && c2 != c ){
   655         -            c2 = sqlite3Utf8Read(&zString);
   656         -            GlobUpperToLower(c2);
   657         -          }
          685  +          cx = sqlite3Toupper(c);
          686  +          c = sqlite3Tolower(c);
   658    687           }else{
   659         -          while( c2 != 0 && c2 != c ){
   660         -            c2 = sqlite3Utf8Read(&zString);
   661         -          }
          688  +          cx = c;
          689  +        }
          690  +        while( (c2 = *(zString++))!=0 ){
          691  +          if( c2!=c && c2!=cx ) continue;
          692  +          if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
   662    693           }
   663         -        if( c2==0 ) return 0;
   664         -        if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
          694  +      }else{
          695  +        while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
          696  +          if( c2!=c ) continue;
          697  +          if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
          698  +        }
   665    699         }
   666    700         return 0;
   667         -    }else if( c==matchOne && !prevEscape ){
   668         -      if( sqlite3Utf8Read(&zString)==0 ){
   669         -        return 0;
   670         -      }
   671         -    }else if( c==matchSet ){
   672         -      u32 prior_c = 0;
   673         -      assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
   674         -      seen = 0;
   675         -      invert = 0;
   676         -      c = sqlite3Utf8Read(&zString);
   677         -      if( c==0 ) return 0;
   678         -      c2 = sqlite3Utf8Read(&zPattern);
   679         -      if( c2=='^' ){
   680         -        invert = 1;
          701  +    }
          702  +    if( c==matchOther ){
          703  +      if( esc ){
          704  +        c = sqlite3Utf8Read(&zPattern);
          705  +        if( c==0 ) return 0;
          706  +        zEscaped = zPattern;
          707  +      }else{
          708  +        u32 prior_c = 0;
          709  +        int seen = 0;
          710  +        int invert = 0;
          711  +        c = sqlite3Utf8Read(&zString);
          712  +        if( c==0 ) return 0;
   681    713           c2 = sqlite3Utf8Read(&zPattern);
   682         -      }
   683         -      if( c2==']' ){
   684         -        if( c==']' ) seen = 1;
   685         -        c2 = sqlite3Utf8Read(&zPattern);
   686         -      }
   687         -      while( c2 && c2!=']' ){
   688         -        if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
          714  +        if( c2=='^' ){
          715  +          invert = 1;
          716  +          c2 = sqlite3Utf8Read(&zPattern);
          717  +        }
          718  +        if( c2==']' ){
          719  +          if( c==']' ) seen = 1;
   689    720             c2 = sqlite3Utf8Read(&zPattern);
   690         -          if( c>=prior_c && c<=c2 ) seen = 1;
   691         -          prior_c = 0;
   692         -        }else{
   693         -          if( c==c2 ){
   694         -            seen = 1;
          721  +        }
          722  +        while( c2 && c2!=']' ){
          723  +          if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
          724  +            c2 = sqlite3Utf8Read(&zPattern);
          725  +            if( c>=prior_c && c<=c2 ) seen = 1;
          726  +            prior_c = 0;
          727  +          }else{
          728  +            if( c==c2 ){
          729  +              seen = 1;
          730  +            }
          731  +            prior_c = c2;
   695    732             }
   696         -          prior_c = c2;
          733  +          c2 = sqlite3Utf8Read(&zPattern);
          734  +        }
          735  +        if( c2==0 || (seen ^ invert)==0 ){
          736  +          return 0;
   697    737           }
   698         -        c2 = sqlite3Utf8Read(&zPattern);
          738  +        continue;
   699    739         }
   700         -      if( c2==0 || (seen ^ invert)==0 ){
   701         -        return 0;
   702         -      }
   703         -    }else if( esc==c && !prevEscape ){
   704         -      prevEscape = 1;
   705         -    }else{
   706         -      c2 = sqlite3Utf8Read(&zString);
   707         -      if( noCase ){
   708         -        GlobUpperToLower(c);
   709         -        GlobUpperToLower(c2);
   710         -      }
   711         -      if( c!=c2 ){
   712         -        return 0;
   713         -      }
   714         -      prevEscape = 0;
   715    740       }
          741  +    c2 = sqlite3Utf8Read(&zString);
          742  +    if( c==c2 ) continue;
          743  +    if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
          744  +      continue;
          745  +    }
          746  +    if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
          747  +    return 0;
   716    748     }
   717    749     return *zString==0;
   718    750   }
   719    751   
   720    752   /*
   721    753   ** The sqlite3_strglob() interface.
   722    754   */

Changes to src/os_unix.c.

  4947   4947   **
  4948   4948   **   *  A constant sqlite3_io_methods object call METHOD that has locking
  4949   4949   **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  4950   4950   **
  4951   4951   **   *  An I/O method finder function called FINDER that returns a pointer
  4952   4952   **      to the METHOD object in the previous bullet.
  4953   4953   */
  4954         -#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
         4954  +#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK, SHMMAP) \
  4955   4955   static const sqlite3_io_methods METHOD = {                                   \
  4956   4956      VERSION,                    /* iVersion */                                \
  4957   4957      CLOSE,                      /* xClose */                                  \
  4958   4958      unixRead,                   /* xRead */                                   \
  4959   4959      unixWrite,                  /* xWrite */                                  \
  4960   4960      unixTruncate,               /* xTruncate */                               \
  4961   4961      unixSync,                   /* xSync */                                   \
................................................................................
  4962   4962      unixFileSize,               /* xFileSize */                               \
  4963   4963      LOCK,                       /* xLock */                                   \
  4964   4964      UNLOCK,                     /* xUnlock */                                 \
  4965   4965      CKLOCK,                     /* xCheckReservedLock */                      \
  4966   4966      unixFileControl,            /* xFileControl */                            \
  4967   4967      unixSectorSize,             /* xSectorSize */                             \
  4968   4968      unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
  4969         -   unixShmMap,                 /* xShmMap */                                 \
         4969  +   SHMMAP,                     /* xShmMap */                                 \
  4970   4970      unixShmLock,                /* xShmLock */                                \
  4971   4971      unixShmBarrier,             /* xShmBarrier */                             \
  4972   4972      unixShmUnmap,               /* xShmUnmap */                               \
  4973   4973      unixFetch,                  /* xFetch */                                  \
  4974   4974      unixUnfetch,                /* xUnfetch */                                \
  4975   4975   };                                                                           \
  4976   4976   static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
................................................................................
  4988   4988   IOMETHODS(
  4989   4989     posixIoFinder,            /* Finder function name */
  4990   4990     posixIoMethods,           /* sqlite3_io_methods object name */
  4991   4991     3,                        /* shared memory and mmap are enabled */
  4992   4992     unixClose,                /* xClose method */
  4993   4993     unixLock,                 /* xLock method */
  4994   4994     unixUnlock,               /* xUnlock method */
  4995         -  unixCheckReservedLock     /* xCheckReservedLock method */
         4995  +  unixCheckReservedLock,    /* xCheckReservedLock method */
         4996  +  unixShmMap                /* xShmMap method */
  4996   4997   )
  4997   4998   IOMETHODS(
  4998   4999     nolockIoFinder,           /* Finder function name */
  4999   5000     nolockIoMethods,          /* sqlite3_io_methods object name */
  5000   5001     3,                        /* shared memory is disabled */
  5001   5002     nolockClose,              /* xClose method */
  5002   5003     nolockLock,               /* xLock method */
  5003   5004     nolockUnlock,             /* xUnlock method */
  5004         -  nolockCheckReservedLock   /* xCheckReservedLock method */
         5005  +  nolockCheckReservedLock,  /* xCheckReservedLock method */
         5006  +  0                         /* xShmMap method */
  5005   5007   )
  5006   5008   IOMETHODS(
  5007   5009     dotlockIoFinder,          /* Finder function name */
  5008   5010     dotlockIoMethods,         /* sqlite3_io_methods object name */
  5009   5011     1,                        /* shared memory is disabled */
  5010   5012     dotlockClose,             /* xClose method */
  5011   5013     dotlockLock,              /* xLock method */
  5012   5014     dotlockUnlock,            /* xUnlock method */
  5013         -  dotlockCheckReservedLock  /* xCheckReservedLock method */
         5015  +  dotlockCheckReservedLock, /* xCheckReservedLock method */
         5016  +  0                         /* xShmMap method */
  5014   5017   )
  5015   5018   
  5016   5019   #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  5017   5020   IOMETHODS(
  5018   5021     flockIoFinder,            /* Finder function name */
  5019   5022     flockIoMethods,           /* sqlite3_io_methods object name */
  5020   5023     1,                        /* shared memory is disabled */
  5021   5024     flockClose,               /* xClose method */
  5022   5025     flockLock,                /* xLock method */
  5023   5026     flockUnlock,              /* xUnlock method */
  5024         -  flockCheckReservedLock    /* xCheckReservedLock method */
         5027  +  flockCheckReservedLock,   /* xCheckReservedLock method */
         5028  +  0                         /* xShmMap method */
  5025   5029   )
  5026   5030   #endif
  5027   5031   
  5028   5032   #if OS_VXWORKS
  5029   5033   IOMETHODS(
  5030   5034     semIoFinder,              /* Finder function name */
  5031   5035     semIoMethods,             /* sqlite3_io_methods object name */
  5032   5036     1,                        /* shared memory is disabled */
  5033   5037     semClose,                 /* xClose method */
  5034   5038     semLock,                  /* xLock method */
  5035   5039     semUnlock,                /* xUnlock method */
  5036         -  semCheckReservedLock      /* xCheckReservedLock method */
         5040  +  semCheckReservedLock,     /* xCheckReservedLock method */
         5041  +  0                         /* xShmMap method */
  5037   5042   )
  5038   5043   #endif
  5039   5044   
  5040   5045   #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  5041   5046   IOMETHODS(
  5042   5047     afpIoFinder,              /* Finder function name */
  5043   5048     afpIoMethods,             /* sqlite3_io_methods object name */
  5044   5049     1,                        /* shared memory is disabled */
  5045   5050     afpClose,                 /* xClose method */
  5046   5051     afpLock,                  /* xLock method */
  5047   5052     afpUnlock,                /* xUnlock method */
  5048         -  afpCheckReservedLock      /* xCheckReservedLock method */
         5053  +  afpCheckReservedLock,     /* xCheckReservedLock method */
         5054  +  0                         /* xShmMap method */
  5049   5055   )
  5050   5056   #endif
  5051   5057   
  5052   5058   /*
  5053   5059   ** The proxy locking method is a "super-method" in the sense that it
  5054   5060   ** opens secondary file descriptors for the conch and lock files and
  5055   5061   ** it uses proxy, dot-file, AFP, and flock() locking methods on those
................................................................................
  5066   5072   IOMETHODS(
  5067   5073     proxyIoFinder,            /* Finder function name */
  5068   5074     proxyIoMethods,           /* sqlite3_io_methods object name */
  5069   5075     1,                        /* shared memory is disabled */
  5070   5076     proxyClose,               /* xClose method */
  5071   5077     proxyLock,                /* xLock method */
  5072   5078     proxyUnlock,              /* xUnlock method */
  5073         -  proxyCheckReservedLock    /* xCheckReservedLock method */
         5079  +  proxyCheckReservedLock,   /* xCheckReservedLock method */
         5080  +  0                         /* xShmMap method */
  5074   5081   )
  5075   5082   #endif
  5076   5083   
  5077   5084   /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  5078   5085   #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  5079   5086   IOMETHODS(
  5080   5087     nfsIoFinder,               /* Finder function name */
  5081   5088     nfsIoMethods,              /* sqlite3_io_methods object name */
  5082   5089     1,                         /* shared memory is disabled */
  5083   5090     unixClose,                 /* xClose method */
  5084   5091     unixLock,                  /* xLock method */
  5085   5092     nfsUnlock,                 /* xUnlock method */
  5086         -  unixCheckReservedLock      /* xCheckReservedLock method */
         5093  +  unixCheckReservedLock,     /* xCheckReservedLock method */
         5094  +  0                          /* xShmMap method */
  5087   5095   )
  5088   5096   #endif
  5089   5097   
  5090   5098   #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  5091   5099   /* 
  5092   5100   ** This "finder" function attempts to determine the best locking strategy 
  5093   5101   ** for the database file "filePath".  It then returns the sqlite3_io_methods

Changes to src/sqliteInt.h.

  2661   2661   /*
  2662   2662   ** Bitfield flags for P5 value in various opcodes.
  2663   2663   **
  2664   2664   ** Note that the values for ISNOOP and LENGTHARG are the same.  But as 
  2665   2665   ** those bits are never used on the same opcode, the overlap is harmless.
  2666   2666   */
  2667   2667   #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
         2668  +#define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
  2668   2669   #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
  2669   2670   #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
  2670   2671   #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
  2671   2672   #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
  2672   2673   #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
  2673   2674   #define OPFLAG_ISNOOP        0x40    /* OP_Delete does pre-update-hook only */
  2674   2675   #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
................................................................................
  2995   2996   # define sqlite3Isspace(x)   isspace((unsigned char)(x))
  2996   2997   # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
  2997   2998   # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
  2998   2999   # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
  2999   3000   # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
  3000   3001   # define sqlite3Tolower(x)   tolower((unsigned char)(x))
  3001   3002   #endif
         3003  +int sqlite3IsIdChar(u8);
  3002   3004   
  3003   3005   /*
  3004   3006   ** Internal function prototypes
  3005   3007   */
  3006   3008   #define sqlite3StrICmp sqlite3_stricmp
  3007   3009   int sqlite3Strlen30(const char*);
  3008   3010   #define sqlite3StrNICmp sqlite3_strnicmp
................................................................................
  3293   3295   void sqlite3CommitTransaction(Parse*);
  3294   3296   void sqlite3RollbackTransaction(Parse*);
  3295   3297   void sqlite3Savepoint(Parse*, int, Token*);
  3296   3298   void sqlite3CloseSavepoints(sqlite3 *);
  3297   3299   void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  3298   3300   int sqlite3ExprIsConstant(Expr*);
  3299   3301   int sqlite3ExprIsConstantNotJoin(Expr*);
  3300         -int sqlite3ExprIsConstantOrFunction(Expr*);
         3302  +int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  3301   3303   int sqlite3ExprIsInteger(Expr*, int*);
  3302   3304   int sqlite3ExprCanBeNull(const Expr*);
  3303   3305   int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  3304   3306   int sqlite3IsRowid(const char*);
  3305   3307   void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
  3306   3308   void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
  3307   3309   int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);

Changes to src/test_multiplex.c.

   998    998         rc = SQLITE_OK;
   999    999         break;
  1000   1000       case SQLITE_FCNTL_SIZE_HINT:
  1001   1001       case SQLITE_FCNTL_CHUNK_SIZE:
  1002   1002         /* no-op these */
  1003   1003         rc = SQLITE_OK;
  1004   1004         break;
         1005  +    case SQLITE_FCNTL_PRAGMA: {
         1006  +      char **aFcntl = (char**)pArg;
         1007  +      if( aFcntl[1] && sqlite3_stricmp(aFcntl[1],"multiplex_truncate")==0 ){
         1008  +        if( aFcntl[2] && aFcntl[2][0] ){
         1009  +          if( sqlite3_stricmp(aFcntl[2], "on")==0
         1010  +           || sqlite3_stricmp(aFcntl[2], "1")==0 ){
         1011  +            pGroup->bTruncate = 1;
         1012  +          }else
         1013  +          if( sqlite3_stricmp(aFcntl[2], "off")==0
         1014  +           || sqlite3_stricmp(aFcntl[2], "0")==0 ){
         1015  +            pGroup->bTruncate = 0;
         1016  +          }
         1017  +        }
         1018  +        aFcntl[0] = sqlite3_mprintf(pGroup->bTruncate ? "on" : "off");
         1019  +        rc = SQLITE_OK;
         1020  +        break;
         1021  +      }
         1022  +      /* If the multiplexor does not handle the pragma, pass it through
         1023  +      ** into the default case. */
         1024  +    }
  1005   1025       default:
  1006   1026         pSubOpen = multiplexSubOpen(pGroup, 0, &rc, NULL, 0);
  1007   1027         if( pSubOpen ){
  1008   1028           rc = pSubOpen->pMethods->xFileControl(pSubOpen, op, pArg);
  1009   1029           if( op==SQLITE_FCNTL_VFSNAME && rc==SQLITE_OK ){
  1010   1030            *(char**)pArg = sqlite3_mprintf("multiplex/%z", *(char**)pArg);
  1011   1031           }

Changes to src/tokenize.c.

    98     98       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
    99     99       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
   100    100       0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
   101    101       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
   102    102   };
   103    103   #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
   104    104   #endif
          105  +int sqlite3IsIdChar(u8 c){ return IdChar(c); }
   105    106   
   106    107   
   107    108   /*
   108    109   ** Return the length of the token that begins at z[0]. 
   109    110   ** Store the token type in *tokenType before returning.
   110    111   */
   111    112   int sqlite3GetToken(const unsigned char *z, int *tokenType){

Changes to src/vdbe.c.

  1563   1563     }
  1564   1564   
  1565   1565     assert( pOp->p4type==P4_FUNCDEF );
  1566   1566     ctx.pFunc = pOp->p4.pFunc;
  1567   1567     ctx.iOp = pc;
  1568   1568     ctx.pVdbe = p;
  1569   1569     MemSetTypeFlag(ctx.pOut, MEM_Null);
  1570         -
  1571   1570     ctx.fErrorOrAux = 0;
  1572         -  if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  1573         -    assert( pOp>aOp );
  1574         -    assert( pOp[-1].p4type==P4_COLLSEQ );
  1575         -    assert( pOp[-1].opcode==OP_CollSeq );
  1576         -    ctx.pColl = pOp[-1].p4.pColl;
  1577         -  }
  1578         -  db->lastRowid = lastRowid;
         1571  +  assert( db->lastRowid==lastRowid );
  1579   1572     (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
  1580         -  lastRowid = db->lastRowid;
         1573  +  lastRowid = db->lastRowid;  /* Remember rowid changes made by xFunc */
  1581   1574   
  1582   1575     /* If the function returned an error, throw an exception */
  1583   1576     if( ctx.fErrorOrAux ){
  1584   1577       if( ctx.isError ){
  1585   1578         sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
  1586   1579         rc = ctx.isError;
  1587   1580       }
................................................................................
  3293   3286     pCur->isOrdered = 1;
  3294   3287     pCur->pgnoRoot = p2;
  3295   3288     rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
  3296   3289     pCur->pKeyInfo = pKeyInfo;
  3297   3290     assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  3298   3291     sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  3299   3292   
  3300         -  /* Since it performs no memory allocation or IO, the only value that
  3301         -  ** sqlite3BtreeCursor() may return is SQLITE_OK. */
  3302         -  assert( rc==SQLITE_OK );
  3303         -
  3304   3293     /* Set the VdbeCursor.isTable variable. Previous versions of
  3305   3294     ** SQLite used to check if the root-page flags were sane at this point
  3306   3295     ** and report database corruption if they were not, but this check has
  3307   3296     ** since moved into the btree layer.  */  
  3308   3297     pCur->isTable = pOp->p4type!=P4_KEYINFO;
  3309   3298     break;
  3310   3299   }
................................................................................
  4030   4019       if( pC->useRandomRowid ){
  4031   4020         /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  4032   4021         ** largest possible integer (9223372036854775807) then the database
  4033   4022         ** engine starts picking positive candidate ROWIDs at random until
  4034   4023         ** it finds one that is not previously used. */
  4035   4024         assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
  4036   4025                                ** an AUTOINCREMENT table. */
  4037         -      /* on the first attempt, simply do one more than previous */
  4038         -      v = lastRowid;
  4039         -      v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  4040         -      v++; /* ensure non-zero */
  4041   4026         cnt = 0;
  4042         -      while(   ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
         4027  +      do{
         4028  +        sqlite3_randomness(sizeof(v), &v);
         4029  +        v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
         4030  +      }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
  4043   4031                                                    0, &res))==SQLITE_OK)
  4044   4032               && (res==0)
  4045         -            && (++cnt<100)){
  4046         -        /* collision - try another random rowid */
  4047         -        sqlite3_randomness(sizeof(v), &v);
  4048         -        if( cnt<5 ){
  4049         -          /* try "small" random rowids for the initial attempts */
  4050         -          v &= 0xffffff;
  4051         -        }else{
  4052         -          v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  4053         -        }
  4054         -        v++; /* ensure non-zero */
  4055         -      }
         4033  +            && (++cnt<100));
  4056   4034         if( rc==SQLITE_OK && res==0 ){
  4057   4035           rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
  4058   4036           goto abort_due_to_error;
  4059   4037         }
  4060   4038         assert( v>0 );  /* EV: R-40812-03570 */
  4061   4039       }
  4062   4040       pC->rowidIsValid = 0;
................................................................................
  5695   5673     ctx.pFunc = pOp->p4.pFunc;
  5696   5674     assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  5697   5675     ctx.pMem = pMem = &aMem[pOp->p3];
  5698   5676     pMem->n++;
  5699   5677     sqlite3VdbeMemInit(&t, db, MEM_Null);
  5700   5678     ctx.pOut = &t;
  5701   5679     ctx.isError = 0;
  5702         -  ctx.pColl = 0;
         5680  +  ctx.pVdbe = p;
         5681  +  ctx.iOp = pc;
  5703   5682     ctx.skipFlag = 0;
  5704         -  if( ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  5705         -    assert( pOp>p->aOp );
  5706         -    assert( pOp[-1].p4type==P4_COLLSEQ );
  5707         -    assert( pOp[-1].opcode==OP_CollSeq );
  5708         -    ctx.pColl = pOp[-1].p4.pColl;
  5709         -  }
  5710   5683     (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
  5711   5684     if( ctx.isError ){
  5712   5685       sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
  5713   5686       rc = ctx.isError;
  5714   5687     }
  5715   5688     if( ctx.skipFlag ){
  5716   5689       assert( pOp[-1].opcode==OP_CollSeq );

Changes to src/vdbeInt.h.

   268    268   ** This structure is defined inside of vdbeInt.h because it uses substructures
   269    269   ** (Mem) which are only defined there.
   270    270   */
   271    271   struct sqlite3_context {
   272    272     Mem *pOut;            /* The return value is stored here */
   273    273     FuncDef *pFunc;       /* Pointer to function information */
   274    274     Mem *pMem;            /* Memory cell used to store aggregate context */
   275         -  CollSeq *pColl;       /* Collating sequence */
   276    275     Vdbe *pVdbe;          /* The VM that owns this context */
   277    276     int iOp;              /* Instruction number of OP_Function */
   278    277     int isError;          /* Error code returned by the function. */
   279    278     u8 skipFlag;          /* Skip accumulator loading if true */
   280    279     u8 fErrorOrAux;       /* isError!=0 or pVdbe->pAuxData modified */
   281    280   };
   282    281   

Changes to src/where.c.

  4355   4355       pNew->u.btree.nEq++;
  4356   4356       pNew->u.btree.nSkip++;
  4357   4357       pNew->aLTerm[pNew->nLTerm++] = 0;
  4358   4358       pNew->wsFlags |= WHERE_SKIPSCAN;
  4359   4359       nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  4360   4360       if( pTerm ){
  4361   4361         /* TUNING:  When estimating skip-scan for a term that is also indexable,
  4362         -      ** increase the cost of the skip-scan by 2x, to make it a little less
         4362  +      ** multiply the cost of the skip-scan by 2.0, to make it a little less
  4363   4363         ** desirable than the regular index lookup. */
  4364   4364         nIter += 10;  assert( 10==sqlite3LogEst(2) );
  4365   4365       }
  4366   4366       pNew->nOut -= nIter;
         4367  +    /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
         4368  +    ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
         4369  +    nIter += 5;
  4367   4370       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  4368   4371       pNew->nOut = saved_nOut;
  4369   4372       pNew->u.btree.nEq = saved_nEq;
  4370   4373       pNew->u.btree.nSkip = saved_nSkip;
  4371   4374     }
  4372   4375     for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  4373   4376       u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
................................................................................
  4714   4717         if( termCanDriveIndex(pTerm, pSrc, 0) ){
  4715   4718           pNew->u.btree.nEq = 1;
  4716   4719           pNew->u.btree.nSkip = 0;
  4717   4720           pNew->u.btree.pIndex = 0;
  4718   4721           pNew->nLTerm = 1;
  4719   4722           pNew->aLTerm[0] = pTerm;
  4720   4723           /* TUNING: One-time cost for computing the automatic index is
  4721         -        ** approximately 7*N*log2(N) where N is the number of rows in
  4722         -        ** the table being indexed. */
  4723         -        pNew->rSetup = rLogSize + rSize + 28;  assert( 28==sqlite3LogEst(7) );
         4724  +        ** estimated to be X*N*log2(N) where N is the number of rows in
         4725  +        ** the table being indexed and where X is 7 (LogEst=28) for normal
         4726  +        ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
         4727  +        ** of X is smaller for views and subqueries so that the query planner
         4728  +        ** will be more aggressive about generating automatic indexes for
         4729  +        ** those objects, since there is no opportunity to add schema
         4730  +        ** indexes on subqueries and views. */
         4731  +        pNew->rSetup = rLogSize + rSize + 4;
         4732  +        if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
         4733  +          pNew->rSetup += 24;
         4734  +        }
  4724   4735           ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  4725   4736           /* TUNING: Each index lookup yields 20 rows in the table.  This
  4726   4737           ** is more than the usual guess of 10 rows, since we have no way
  4727   4738           ** of knowing how selective the index will ultimately be.  It would
  4728   4739           ** not be unreasonable to make this value much larger. */
  4729   4740           pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
  4730   4741           pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);

Changes to test/autoindex1.test.

   408    408     EXPLAIN QUERY PLAN
   409    409     SELECT * FROM 
   410    410           data JOIN mimetypes ON (data.mimetype_id=mimetypes._id) 
   411    411                JOIN raw_contacts ON (data.raw_contact_id=raw_contacts._id) 
   412    412                JOIN accounts ON (raw_contacts.account_id=accounts._id)
   413    413      WHERE mimetypes._id=10 AND data14 IS NOT NULL;
   414    414   } {/SEARCH TABLE data .*SEARCH TABLE raw_contacts/}
          415  +
          416  +# Another test case from an important user of SQLite.  The key feature of
          417  +# this test is that the "aggindex" subquery should make use of an
          418  +# automatic index.  If it does, the query is fast.  If it does not, the
          419  +# query is deathly slow.  It worked OK in 3.7.17 but started going slow
          420  +# with version 3.8.0.  The problem was fixed for 3.8.7 by reducing the
          421  +# cost estimate for automatic indexes on views and subqueries.
          422  +#
          423  +db close
          424  +forcedelete test.db
          425  +sqlite3 db test.db
          426  +do_execsql_test autoindex1-900 {
          427  +  CREATE TABLE messages (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, message_id, document_id BLOB, in_reply_to, remote_id INTEGER, sender INTEGER, subject_prefix, subject INTEGER, date_sent INTEGER, date_received INTEGER, date_created INTEGER, date_last_viewed INTEGER, mailbox INTEGER, remote_mailbox INTEGER, original_mailbox INTEGER, flags INTEGER, read, flagged, size INTEGER, color, encoding, type INTEGER, pad, conversation_id INTEGER DEFAULT -1, snippet TEXT DEFAULT NULL, fuzzy_ancestor INTEGER DEFAULT NULL, automated_conversation INTEGER DEFAULT 0, root_status INTEGER DEFAULT -1, conversation_position INTEGER DEFAULT -1);
          428  +  CREATE INDEX date_index ON messages(date_received);
          429  +  CREATE INDEX date_last_viewed_index ON messages(date_last_viewed);
          430  +  CREATE INDEX date_created_index ON messages(date_created);
          431  +  CREATE INDEX message_message_id_mailbox_index ON messages(message_id, mailbox);
          432  +  CREATE INDEX message_document_id_index ON messages(document_id);
          433  +  CREATE INDEX message_read_index ON messages(read);
          434  +  CREATE INDEX message_flagged_index ON messages(flagged);
          435  +  CREATE INDEX message_mailbox_index ON messages(mailbox, date_received);
          436  +  CREATE INDEX message_remote_mailbox_index ON messages(remote_mailbox, remote_id);
          437  +  CREATE INDEX message_type_index ON messages(type);
          438  +  CREATE INDEX message_conversation_id_conversation_position_index ON messages(conversation_id, conversation_position);
          439  +  CREATE INDEX message_fuzzy_ancestor_index ON messages(fuzzy_ancestor);
          440  +  CREATE INDEX message_subject_fuzzy_ancestor_index ON messages(subject, fuzzy_ancestor);
          441  +  CREATE INDEX message_sender_subject_automated_conversation_index ON messages(sender, subject, automated_conversation);
          442  +  CREATE INDEX message_sender_index ON messages(sender);
          443  +  CREATE INDEX message_root_status ON messages(root_status);
          444  +  CREATE TABLE subjects (ROWID INTEGER PRIMARY KEY, subject COLLATE RTRIM, normalized_subject COLLATE RTRIM);
          445  +  CREATE INDEX subject_subject_index ON subjects(subject);
          446  +  CREATE INDEX subject_normalized_subject_index ON subjects(normalized_subject);
          447  +  CREATE TABLE addresses (ROWID INTEGER PRIMARY KEY, address COLLATE NOCASE, comment, UNIQUE(address, comment));
          448  +  CREATE INDEX addresses_address_index ON addresses(address);
          449  +  CREATE TABLE mailboxes (ROWID INTEGER PRIMARY KEY, url UNIQUE, total_count INTEGER DEFAULT 0, unread_count INTEGER DEFAULT 0, unseen_count INTEGER DEFAULT 0, deleted_count INTEGER DEFAULT 0, unread_count_adjusted_for_duplicates INTEGER DEFAULT 0, change_identifier, source INTEGER, alleged_change_identifier);
          450  +  CREATE INDEX mailboxes_source_index ON mailboxes(source);
          451  +  CREATE TABLE labels (ROWID INTEGER PRIMARY KEY, message_id INTEGER NOT NULL, mailbox_id INTEGER NOT NULL, UNIQUE(message_id, mailbox_id));
          452  +  CREATE INDEX labels_message_id_mailbox_id_index ON labels(message_id, mailbox_id);
          453  +  CREATE INDEX labels_mailbox_id_index ON labels(mailbox_id);
          454  +  
          455  +  explain query plan
          456  +  SELECT messages.ROWID,
          457  +         messages.message_id,
          458  +         messages.remote_id,
          459  +         messages.date_received,
          460  +         messages.date_sent,
          461  +         messages.flags,
          462  +         messages.size,
          463  +         messages.color,
          464  +         messages.date_last_viewed,
          465  +         messages.subject_prefix,
          466  +         subjects.subject,
          467  +         sender.comment,
          468  +         sender.address,
          469  +         NULL,
          470  +         messages.mailbox,
          471  +         messages.original_mailbox,
          472  +         NULL,
          473  +         NULL,
          474  +         messages.type,
          475  +         messages.document_id,
          476  +         sender,
          477  +         NULL,
          478  +         messages.conversation_id,
          479  +         messages.conversation_position,
          480  +         agglabels.labels
          481  +   FROM mailboxes AS mailbox
          482  +        JOIN messages ON mailbox.ROWID = messages.mailbox
          483  +        LEFT OUTER JOIN subjects ON messages.subject = subjects.ROWID
          484  +        LEFT OUTER JOIN addresses AS sender ON messages.sender = sender.ROWID
          485  +        LEFT OUTER JOIN (
          486  +               SELECT message_id, group_concat(mailbox_id) as labels
          487  +               FROM labels GROUP BY message_id
          488  +             ) AS agglabels ON messages.ROWID = agglabels.message_id
          489  +  WHERE (mailbox.url = 'imap://email.app@imap.gmail.com/%5BGmail%5D/All%20Mail')
          490  +    AND (messages.ROWID IN (
          491  +            SELECT labels.message_id
          492  +              FROM labels JOIN mailboxes ON labels.mailbox_id = mailboxes.ROWID
          493  +             WHERE mailboxes.url = 'imap://email.app@imap.gmail.com/INBOX'))
          494  +    AND messages.mailbox in (6,12,18,24,30,36,42,1,7,13,19,25,31,37,43,2,8,
          495  +                             14,20,26,32,38,3,9,15,21,27,33,39,4,10,16,22,28,
          496  +                             34,40,5,11,17,23,35,41)
          497  +   ORDER BY date_received DESC;
          498  +} {/agglabels USING AUTOMATIC COVERING INDEX/}
          499  +
          500  +# A test case for VIEWs
          501  +#
          502  +do_execsql_test autoindex1-901 {
          503  +  CREATE TABLE t1(x INTEGER PRIMARY KEY, y, z);
          504  +  CREATE TABLE t2(a, b);
          505  +  CREATE VIEW agg2 AS SELECT a, sum(b) AS m FROM t2 GROUP BY a;
          506  +  EXPLAIN QUERY PLAN
          507  +  SELECT t1.z, agg2.m
          508  +    FROM t1 JOIN agg2 ON t1.y=agg2.m
          509  +   WHERE t1.x IN (1,2,3);
          510  +} {/USING AUTOMATIC COVERING INDEX/}
          511  +
   415    512   
   416    513   finish_test

Changes to test/default.test.

    94     94       f INT DEFAULT -9223372036854775808,
    95     95       g INT DEFAULT (-(-9223372036854775808)),
    96     96       h INT DEFAULT (-(-9223372036854775807))
    97     97     );
    98     98     INSERT INTO t300 DEFAULT VALUES;
    99     99     SELECT * FROM t300;
   100    100   } {2147483647 2147483648 9223372036854775807 -2147483647 -2147483648 -9223372036854775808 9.22337203685478e+18 9223372036854775807}
          101  +
          102  +# Do now allow bound parameters in new DEFAULT values. 
          103  +# Silently convert bound parameters to NULL in DEFAULT causes
          104  +# in the sqlite_master table, for backwards compatibility.
          105  +#
          106  +db close
          107  +forcedelete test.db
          108  +sqlite3 db test.db
          109  +do_execsql_test default-4.0 {
          110  +  CREATE TABLE t1(a TEXT, b TEXT DEFAULT(99));
          111  +  PRAGMA writable_schema=ON;
          112  +  UPDATE sqlite_master SET sql='CREATE TABLE t1(a TEXT, b TEXT DEFAULT(:xyz))';
          113  +} {}
          114  +db close 
          115  +sqlite3 db test.db
          116  +do_execsql_test default-4.1 {
          117  +  INSERT INTO t1(a) VALUES('xyzzy');
          118  +  SELECT a, quote(b) FROM t1;
          119  +} {xyzzy NULL}
          120  +do_catchsql_test default-4.2 {
          121  +  CREATE TABLE t2(a TEXT, b TEXT DEFAULT(:xyz));
          122  +} {1 {default value of column [b] is not constant}}
          123  +do_catchsql_test default-4.3 {
          124  +  CREATE TABLE t2(a TEXT, b TEXT DEFAULT(abs(:xyz)));
          125  +} {1 {default value of column [b] is not constant}}
          126  +do_catchsql_test default-4.4 {
          127  +  CREATE TABLE t2(a TEXT, b TEXT DEFAULT(98+coalesce(5,:xyz)));
          128  +} {1 {default value of column [b] is not constant}}
   101    129   
   102    130   finish_test

Added test/multiplex4.test.

            1  +# 2014-09-25
            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  +# This file contains tests for the "truncate" option in the multiplexor.
           13  +#
           14  +
           15  +set testdir [file dirname $argv0]
           16  +source $testdir/tester.tcl
           17  +set ::testprefix multiplex4
           18  +
           19  +db close
           20  +sqlite3_shutdown
           21  +sqlite3_multiplex_initialize {} 0
           22  +
           23  +# delete all filesl with the base name of $basename
           24  +#
           25  +proc multiplex_delete_db {basename} {
           26  +  foreach file [glob -nocomplain $basename.*] {
           27  +    forcedelete $file
           28  +  }
           29  +}
           30  +
           31  +# Return a sorted list of all files with the base name of $basename.
           32  +# Except, delete all text from the end of $basename through the NNN
           33  +# suffix on the end of the filename.
           34  +#
           35  +proc multiplex_file_list {basename} {
           36  +  set x {}
           37  +  foreach file [glob -nocomplain $basename.*] {
           38  +    regsub "^$basename\\..*(\\d\\d\\d)\$" $file $basename.\\1 file
           39  +    lappend x $file
           40  +  }
           41  +  return [lsort $x]
           42  +}
           43  +
           44  +do_test multiplex4-1.0 {
           45  +  multiplex_delete_db mx4test
           46  +  sqlite3 db {file:mx4test.db?chunksize=10&truncate=1} -uri 1 -vfs multiplex
           47  +  db eval {
           48  +    CREATE TABLE t1(x);
           49  +    INSERT INTO t1(x) VALUES(randomblob(250000));
           50  +  }
           51  +  multiplex_file_list mx4test
           52  +} {mx4test.001 mx4test.db}
           53  +
           54  +do_test multiplex4-1.1 {
           55  +  db eval {
           56  +    DELETE FROM t1;
           57  +    VACUUM;
           58  +  }
           59  +  multiplex_file_list mx4test
           60  +} {mx4test.db}
           61  +
           62  +do_test multiplex4-1.2 {
           63  +  db eval {PRAGMA multiplex_truncate}
           64  +} {on}
           65  +do_test multiplex4-1.3 {
           66  +  db eval {PRAGMA multiplex_truncate=off}
           67  +} {off}
           68  +do_test multiplex4-1.4 {
           69  +  db eval {PRAGMA multiplex_truncate}
           70  +} {off}
           71  +do_test multiplex4-1.5 {
           72  +  db eval {PRAGMA multiplex_truncate=on}
           73  +} {on}
           74  +do_test multiplex4-1.6 {
           75  +  db eval {PRAGMA multiplex_truncate}
           76  +} {on}
           77  +do_test multiplex4-1.7 {
           78  +  db eval {PRAGMA multiplex_truncate=0}
           79  +} {off}
           80  +do_test multiplex4-1.8 {
           81  +  db eval {PRAGMA multiplex_truncate=1}
           82  +} {on}
           83  +do_test multiplex4-1.9 {
           84  +  db eval {PRAGMA multiplex_truncate=0}
           85  +} {off}
           86  +
           87  +do_test multiplex4-1.10 {
           88  +  db eval {
           89  +    INSERT INTO t1(x) VALUES(randomblob(250000));
           90  +  }
           91  +  multiplex_file_list mx4test
           92  +} {mx4test.001 mx4test.db}
           93  +
           94  +do_test multiplex4-1.11 {
           95  +  db eval {
           96  +    DELETE FROM t1;
           97  +    VACUUM;
           98  +  }
           99  +  multiplex_file_list mx4test
          100  +} {mx4test.001 mx4test.db}
          101  +
          102  +do_test multiplex4-1.12 {
          103  +  db eval {
          104  +    PRAGMA multiplex_truncate=ON;
          105  +    DROP TABLE t1;
          106  +    VACUUM;
          107  +  }
          108  +  multiplex_file_list mx4test
          109  +} {mx4test.db}
          110  +
          111  +catch { db close }
          112  +forcedelete mx4test.db
          113  +sqlite3_multiplex_shutdown
          114  +finish_test

Changes to test/rowid.test.

   675    675   } {a}
   676    676   do_test rowid-12.2 {
   677    677     db close
   678    678     sqlite3 db test.db
   679    679     save_prng_state
   680    680     execsql {
   681    681       INSERT INTO t7 VALUES(NULL,'b');
   682         -    SELECT x, y FROM t7;
          682  +    SELECT x, y FROM t7 ORDER BY x;
   683    683     }
   684         -} {1 b 9223372036854775807 a}
          684  +} {/\d+ b 9223372036854775807 a/}
   685    685   execsql {INSERT INTO t7 VALUES(2,'y');}
   686    686   for {set i 1} {$i<100} {incr i} {
   687    687     do_test rowid-12.3.$i {
   688    688       db eval {DELETE FROM t7temp; INSERT INTO t7temp VALUES(1);}
   689    689       restore_prng_state
   690    690       execsql {
   691    691         INSERT INTO t7 VALUES(NULL,'x');
................................................................................
   697    697     db eval {DELETE FROM t7temp; INSERT INTO t7temp VALUES(1);}
   698    698     restore_prng_state
   699    699     catchsql {
   700    700       INSERT INTO t7 VALUES(NULL,'x');
   701    701     }
   702    702   } {1 {database or disk is full}}
   703    703   
          704  +# INSERTs that happen inside of nested function calls are recorded
          705  +# by last_insert_rowid.
          706  +#
          707  +proc rowid_addrow_func {n} {
          708  +  db eval {INSERT INTO t13(rowid,x) VALUES($n,$n*$n)}
          709  +  return [db last_insert_rowid]
          710  +}
          711  +db function addrow rowid_addrow_func
          712  +do_execsql_test rowid-13.1 {
          713  +  CREATE TABLE t13(x);
          714  +  INSERT INTO t13(rowid,x) VALUES(1234,5);
          715  +  SELECT rowid, x, addrow(rowid+1000), '|' FROM t13 LIMIT 3;
          716  +  SELECT last_insert_rowid();
          717  +} {1234 5 2234 | 2234 4990756 3234 | 3234 10458756 4234 | 4234}
   704    718   
   705    719   finish_test

Changes to test/skipscan1.test.

   241    241   } {}
   242    242   db cache flush
   243    243   do_execsql_test skipscan1-5.3 {
   244    244     EXPLAIN QUERY PLAN
   245    245       SELECT xh, loc FROM t5 WHERE loc >= 'M' AND loc < 'N';
   246    246   } {/.*COVERING INDEX t5i1 .*/}
   247    247   
   248         -
          248  +# The column used by the skip-scan needs to be sufficiently selective.
          249  +# See the private email from Adi Zaimi to drh@sqlite.org on 2014-09-22.
          250  +#
          251  +db close
          252  +forcedelete test.db
          253  +sqlite3 db test.db
          254  +do_execsql_test skipscan1-6.1 {
          255  +  CREATE TABLE t1(a,b,c,d,e,f,g,h varchar(300));
          256  +  CREATE INDEX t1ab ON t1(a,b);
          257  +  ANALYZE sqlite_master;
          258  +  -- Only two distinct values for the skip-scan column.  Skip-scan is not used.
          259  +  INSERT INTO sqlite_stat1 VALUES('t1','t1ab','500000 250000 125000');
          260  +  ANALYZE sqlite_master;
          261  +  EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE b=1;
          262  +} {~/ANY/}
          263  +do_execsql_test skipscan1-6.2 {
          264  +  -- Four distinct values for the skip-scan column.  Skip-scan is used.
          265  +  UPDATE sqlite_stat1 SET stat='500000 250000 62500';
          266  +  ANALYZE sqlite_master;
          267  +  EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE b=1;
          268  +} {/ANY.a. AND b=/}
          269  +do_execsql_test skipscan1-6.3 {
          270  +  -- Two distinct values for the skip-scan column again.  Skip-scan is not used.
          271  +  UPDATE sqlite_stat1 SET stat='500000 125000 62500';
          272  +  ANALYZE sqlite_master;
          273  +  EXPLAIN QUERY PLAN SELECT * FROM t1 WHERE b=1;
          274  +} {~/ANY/}
   249    275   
   250    276   finish_test

Changes to test/skipscan5.test.

   104    104   
   105    105     foreach {tn2 q res} {
   106    106       1 { c BETWEEN 'd' AND 'e' }       {/*ANY(a) AND ANY(b) AND c>? AND c<?*/}
   107    107       2 { c BETWEEN 'b' AND 'r' }       {/*SCAN TABLE t2*/}
   108    108       3 { c > 'q' }                     {/*ANY(a) AND ANY(b) AND c>?*/}
   109    109       4 { c > 'e' }                     {/*SCAN TABLE t2*/}
   110    110       5 { c < 'q' }                     {/*SCAN TABLE t2*/}
   111         -    4 { c < 'e' }                     {/*ANY(a) AND ANY(b) AND c<?*/}
          111  +    6 { c < 'c' }                     {/*ANY(a) AND ANY(b) AND c<?*/}
   112    112     } {
   113    113       set sql "EXPLAIN QUERY PLAN SELECT * FROM t2 WHERE $q" 
   114    114       do_execsql_test 2.$tn.$tn2 $sql $res
   115    115     }
   116    116   
   117    117   }
   118    118   
................................................................................
   176    176     6 "b < 'zzz'"                        {/*SCAN TABLE t3*/}
   177    177   } {
   178    178     set sql "EXPLAIN QUERY PLAN SELECT * FROM t3 WHERE $q" 
   179    179     do_execsql_test 3.3.$tn $sql $res
   180    180   }
   181    181   
   182    182   finish_test
   183         -
   184         -
   185         -
   186         -