xref: /sqlite-3.40.0/src/where.c (revision 7d913e9a)
175897234Sdrh /*
2b19a2bc6Sdrh ** 2001 September 15
375897234Sdrh **
4b19a2bc6Sdrh ** The author disclaims copyright to this source code.  In place of
5b19a2bc6Sdrh ** a legal notice, here is a blessing:
675897234Sdrh **
7b19a2bc6Sdrh **    May you do good and not evil.
8b19a2bc6Sdrh **    May you find forgiveness for yourself and forgive others.
9b19a2bc6Sdrh **    May you share freely, never taking more than you give.
1075897234Sdrh **
1175897234Sdrh *************************************************************************
1275897234Sdrh ** This module contains C code that generates VDBE code used to process
13909626d4Sdrh ** the WHERE clause of SQL statements.  This module is responsible for
1451669863Sdrh ** generating the code that loops through a table looking for applicable
1551669863Sdrh ** rows.  Indices are selected and used to speed the search when doing
1651669863Sdrh ** so is applicable.  Because this module is responsible for selecting
1751669863Sdrh ** indices, you might also think of this module as the "query optimizer".
1875897234Sdrh */
1975897234Sdrh #include "sqliteInt.h"
20e54df42dSdrh #include "whereInt.h"
2151147baaSdrh 
22efc88d02Sdrh /*
23efc88d02Sdrh ** Extra information appended to the end of sqlite3_index_info but not
24efc88d02Sdrh ** visible to the xBestIndex function, at least not directly.  The
25efc88d02Sdrh ** sqlite3_vtab_collation() interface knows how to reach it, however.
26efc88d02Sdrh **
27efc88d02Sdrh ** This object is not an API and can be changed from one release to the
28efc88d02Sdrh ** next.  As long as allocateIndexInfo() and sqlite3_vtab_collation()
29efc88d02Sdrh ** agree on the structure, all will be well.
30efc88d02Sdrh */
31efc88d02Sdrh typedef struct HiddenIndexInfo HiddenIndexInfo;
32efc88d02Sdrh struct HiddenIndexInfo {
33efc88d02Sdrh   WhereClause *pWC;        /* The Where clause being analyzed */
34efc88d02Sdrh   Parse *pParse;           /* The parsing context */
35ec778d27Sdrh   int eDistinct;           /* Value to return from sqlite3_vtab_distinct() */
360fe7e7d9Sdrh   u32 mIn;                 /* Mask of terms that are <col> IN (...) */
370fe7e7d9Sdrh   u32 mHandleIn;           /* Terms that vtab will handle as <col> IN (...) */
3882801a5bSdrh   sqlite3_value *aRhs[1];  /* RHS values for constraints. MUST BE LAST
3982801a5bSdrh                            ** because extra space is allocated to hold up
4082801a5bSdrh                            ** to nTerm such values */
41efc88d02Sdrh };
42efc88d02Sdrh 
436f82e85aSdrh /* Forward declaration of methods */
446f82e85aSdrh static int whereLoopResize(sqlite3*, WhereLoop*, int);
456f82e85aSdrh 
4651147baaSdrh /*
476f32848dSdrh ** Return the estimated number of output rows from a WHERE clause
486f32848dSdrh */
sqlite3WhereOutputRowCount(WhereInfo * pWInfo)49c3489bbfSdrh LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
50c3489bbfSdrh   return pWInfo->nRowOut;
516f32848dSdrh }
526f32848dSdrh 
536f32848dSdrh /*
546f32848dSdrh ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
556f32848dSdrh ** WHERE clause returns outputs for DISTINCT processing.
566f32848dSdrh */
sqlite3WhereIsDistinct(WhereInfo * pWInfo)576f32848dSdrh int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
586f32848dSdrh   return pWInfo->eDistinct;
596f32848dSdrh }
606f32848dSdrh 
616f32848dSdrh /*
62c37b7680Sdrh ** Return the number of ORDER BY terms that are satisfied by the
63c37b7680Sdrh ** WHERE clause.  A return of 0 means that the output must be
64c37b7680Sdrh ** completely sorted.  A return equal to the number of ORDER BY
65c37b7680Sdrh ** terms means that no sorting is needed at all.  A return that
66c37b7680Sdrh ** is positive but less than the number of ORDER BY terms means that
67c37b7680Sdrh ** block sorting is required.
686f32848dSdrh */
sqlite3WhereIsOrdered(WhereInfo * pWInfo)696f32848dSdrh int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
70ddba0c22Sdrh   return pWInfo->nOBSat;
716f32848dSdrh }
726f32848dSdrh 
736f32848dSdrh /*
746ee5a7b4Sdrh ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
756ee5a7b4Sdrh ** to emit rows in increasing order, and if the last row emitted by the
766ee5a7b4Sdrh ** inner-most loop did not fit within the sorter, then we can skip all
776ee5a7b4Sdrh ** subsequent rows for the current iteration of the inner loop (because they
786ee5a7b4Sdrh ** will not fit in the sorter either) and continue with the second inner
796ee5a7b4Sdrh ** loop - the loop immediately outside the inner-most.
80a536df4eSdrh **
816ee5a7b4Sdrh ** When a row does not fit in the sorter (because the sorter already
826ee5a7b4Sdrh ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
836ee5a7b4Sdrh ** label returned by this function.
846ee5a7b4Sdrh **
856ee5a7b4Sdrh ** If the ORDER BY LIMIT optimization applies, the jump destination should
866ee5a7b4Sdrh ** be the continuation for the second-inner-most loop.  If the ORDER BY
876ee5a7b4Sdrh ** LIMIT optimization does not apply, then the jump destination should
886ee5a7b4Sdrh ** be the continuation for the inner-most loop.
896ee5a7b4Sdrh **
906ee5a7b4Sdrh ** It is always safe for this routine to return the continuation of the
916ee5a7b4Sdrh ** inner-most loop, in the sense that a correct answer will result.
926ee5a7b4Sdrh ** Returning the continuation the second inner loop is an optimization
936ee5a7b4Sdrh ** that might make the code run a little faster, but should not change
946ee5a7b4Sdrh ** the final answer.
95a536df4eSdrh */
sqlite3WhereOrderByLimitOptLabel(WhereInfo * pWInfo)966ee5a7b4Sdrh int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
976ee5a7b4Sdrh   WhereLevel *pInner;
986ee5a7b4Sdrh   if( !pWInfo->bOrderedInnerLoop ){
996ee5a7b4Sdrh     /* The ORDER BY LIMIT optimization does not apply.  Jump to the
1006ee5a7b4Sdrh     ** continuation of the inner-most loop. */
1016ee5a7b4Sdrh     return pWInfo->iContinue;
1026ee5a7b4Sdrh   }
1036ee5a7b4Sdrh   pInner = &pWInfo->a[pWInfo->nLevel-1];
104f7ded147Sdrh   assert( pInner->addrNxt!=0 );
105ecb386b7Sdrh   return pInner->pRJ ? pWInfo->iContinue : pInner->addrNxt;
106a536df4eSdrh }
107a536df4eSdrh 
108a536df4eSdrh /*
109d193057aSdrh ** While generating code for the min/max optimization, after handling
110d193057aSdrh ** the aggregate-step call to min() or max(), check to see if any
111d193057aSdrh ** additional looping is required.  If the output order is such that
112d193057aSdrh ** we are certain that the correct answer has already been found, then
113d193057aSdrh ** code an OP_Goto to by pass subsequent processing.
114d193057aSdrh **
115d193057aSdrh ** Any extra OP_Goto that is coded here is an optimization.  The
116d193057aSdrh ** correct answer should be obtained regardless.  This OP_Goto just
117d193057aSdrh ** makes the answer appear faster.
118d193057aSdrh */
sqlite3WhereMinMaxOptEarlyOut(Vdbe * v,WhereInfo * pWInfo)119d193057aSdrh void sqlite3WhereMinMaxOptEarlyOut(Vdbe *v, WhereInfo *pWInfo){
120d193057aSdrh   WhereLevel *pInner;
1215870dc80Sdrh   int i;
122d193057aSdrh   if( !pWInfo->bOrderedInnerLoop ) return;
123d193057aSdrh   if( pWInfo->nOBSat==0 ) return;
1245870dc80Sdrh   for(i=pWInfo->nLevel-1; i>=0; i--){
1255870dc80Sdrh     pInner = &pWInfo->a[i];
1265870dc80Sdrh     if( (pInner->pWLoop->wsFlags & WHERE_COLUMN_IN)!=0 ){
127d193057aSdrh       sqlite3VdbeGoto(v, pInner->addrNxt);
1285870dc80Sdrh       return;
129d193057aSdrh     }
130d193057aSdrh   }
1315870dc80Sdrh   sqlite3VdbeGoto(v, pWInfo->iBreak);
1325870dc80Sdrh }
133d193057aSdrh 
134d193057aSdrh /*
1356f32848dSdrh ** Return the VDBE address or label to jump to in order to continue
1366f32848dSdrh ** immediately with the next row of a WHERE clause.
1376f32848dSdrh */
sqlite3WhereContinueLabel(WhereInfo * pWInfo)1386f32848dSdrh int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
139a22a75e5Sdrh   assert( pWInfo->iContinue!=0 );
1406f32848dSdrh   return pWInfo->iContinue;
1416f32848dSdrh }
1426f32848dSdrh 
1436f32848dSdrh /*
1446f32848dSdrh ** Return the VDBE address or label to jump to in order to break
1456f32848dSdrh ** out of a WHERE loop.
1466f32848dSdrh */
sqlite3WhereBreakLabel(WhereInfo * pWInfo)1476f32848dSdrh int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
1486f32848dSdrh   return pWInfo->iBreak;
1496f32848dSdrh }
1506f32848dSdrh 
1516f32848dSdrh /*
152b0264eecSdrh ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
153be3da241Sdrh ** operate directly on the rowids returned by a WHERE clause.  Return
154b0264eecSdrh ** ONEPASS_SINGLE (1) if the statement can operation directly because only
155b0264eecSdrh ** a single row is to be changed.  Return ONEPASS_MULTI (2) if the one-pass
156b0264eecSdrh ** optimization can be used on multiple
157fc8d4f96Sdrh **
158fc8d4f96Sdrh ** If the ONEPASS optimization is used (if this routine returns true)
159fc8d4f96Sdrh ** then also write the indices of open cursors used by ONEPASS
160fc8d4f96Sdrh ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
161fc8d4f96Sdrh ** table and iaCur[1] gets the cursor used by an auxiliary index.
162fc8d4f96Sdrh ** Either value may be -1, indicating that cursor is not used.
163fc8d4f96Sdrh ** Any cursors returned will have been opened for writing.
164fc8d4f96Sdrh **
165fc8d4f96Sdrh ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
166fc8d4f96Sdrh ** unable to use the ONEPASS optimization.
1676f32848dSdrh */
sqlite3WhereOkOnePass(WhereInfo * pWInfo,int * aiCur)168fc8d4f96Sdrh int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
169fc8d4f96Sdrh   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
170a722821eSdrh #ifdef WHERETRACE_ENABLED
171a722821eSdrh   if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
172a722821eSdrh     sqlite3DebugPrintf("%s cursors: %d %d\n",
173a722821eSdrh          pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
174a722821eSdrh          aiCur[0], aiCur[1]);
175a722821eSdrh   }
176a722821eSdrh #endif
177b0264eecSdrh   return pWInfo->eOnePass;
1786f32848dSdrh }
1796f32848dSdrh 
1806f32848dSdrh /*
181be3da241Sdrh ** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move
182be3da241Sdrh ** the data cursor to the row selected by the index cursor.
183be3da241Sdrh */
sqlite3WhereUsesDeferredSeek(WhereInfo * pWInfo)184be3da241Sdrh int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){
185be3da241Sdrh   return pWInfo->bDeferredSeek;
186be3da241Sdrh }
187be3da241Sdrh 
188be3da241Sdrh /*
189aa32e3c6Sdrh ** Move the content of pSrc into pDest
190aa32e3c6Sdrh */
whereOrMove(WhereOrSet * pDest,WhereOrSet * pSrc)191aa32e3c6Sdrh static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
192aa32e3c6Sdrh   pDest->n = pSrc->n;
193aa32e3c6Sdrh   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
194aa32e3c6Sdrh }
195aa32e3c6Sdrh 
196aa32e3c6Sdrh /*
197aa32e3c6Sdrh ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
198aa32e3c6Sdrh **
199aa32e3c6Sdrh ** The new entry might overwrite an existing entry, or it might be
200aa32e3c6Sdrh ** appended, or it might be discarded.  Do whatever is the right thing
201aa32e3c6Sdrh ** so that pSet keeps the N_OR_COST best entries seen so far.
202aa32e3c6Sdrh */
whereOrInsert(WhereOrSet * pSet,Bitmask prereq,LogEst rRun,LogEst nOut)203aa32e3c6Sdrh static int whereOrInsert(
204aa32e3c6Sdrh   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
205aa32e3c6Sdrh   Bitmask prereq,        /* Prerequisites of the new entry */
206bf539c4dSdrh   LogEst rRun,           /* Run-cost of the new entry */
207bf539c4dSdrh   LogEst nOut            /* Number of outputs for the new entry */
208aa32e3c6Sdrh ){
209aa32e3c6Sdrh   u16 i;
210aa32e3c6Sdrh   WhereOrCost *p;
211aa32e3c6Sdrh   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
212aa32e3c6Sdrh     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
213aa32e3c6Sdrh       goto whereOrInsert_done;
214aa32e3c6Sdrh     }
215aa32e3c6Sdrh     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
216aa32e3c6Sdrh       return 0;
217aa32e3c6Sdrh     }
218aa32e3c6Sdrh   }
219aa32e3c6Sdrh   if( pSet->n<N_OR_COST ){
220aa32e3c6Sdrh     p = &pSet->a[pSet->n++];
221aa32e3c6Sdrh     p->nOut = nOut;
222aa32e3c6Sdrh   }else{
223aa32e3c6Sdrh     p = pSet->a;
224aa32e3c6Sdrh     for(i=1; i<pSet->n; i++){
225aa32e3c6Sdrh       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
226aa32e3c6Sdrh     }
227aa32e3c6Sdrh     if( p->rRun<=rRun ) return 0;
228aa32e3c6Sdrh   }
229aa32e3c6Sdrh whereOrInsert_done:
230aa32e3c6Sdrh   p->prereq = prereq;
231aa32e3c6Sdrh   p->rRun = rRun;
232aa32e3c6Sdrh   if( p->nOut>nOut ) p->nOut = nOut;
233aa32e3c6Sdrh   return 1;
234aa32e3c6Sdrh }
235aa32e3c6Sdrh 
236aa32e3c6Sdrh /*
2371398ad36Sdrh ** Return the bitmask for the given cursor number.  Return 0 if
2381398ad36Sdrh ** iCursor is not in the set.
2396a3ea0e6Sdrh */
sqlite3WhereGetMask(WhereMaskSet * pMaskSet,int iCursor)2406f82e85aSdrh Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
2416a3ea0e6Sdrh   int i;
242fcd71b60Sdrh   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
243dae2a109Sdrh   assert( pMaskSet->n>0 || pMaskSet->ix[0]<0 );
244dae2a109Sdrh   assert( iCursor>=-1 );
245844a89b5Sdrh   if( pMaskSet->ix[0]==iCursor ){
246844a89b5Sdrh     return 1;
247844a89b5Sdrh   }
248844a89b5Sdrh   for(i=1; i<pMaskSet->n; i++){
24951669863Sdrh     if( pMaskSet->ix[i]==iCursor ){
2507699d1c4Sdrh       return MASKBIT(i);
25151669863Sdrh     }
2526a3ea0e6Sdrh   }
2536a3ea0e6Sdrh   return 0;
2546a3ea0e6Sdrh }
2556a3ea0e6Sdrh 
256f8bdcfa3Sdrh /* Allocate memory that is automatically freed when pWInfo is freed.
257f8bdcfa3Sdrh */
sqlite3WhereMalloc(WhereInfo * pWInfo,u64 nByte)258f8bdcfa3Sdrh void *sqlite3WhereMalloc(WhereInfo *pWInfo, u64 nByte){
259f8bdcfa3Sdrh   WhereMemBlock *pBlock;
260f8bdcfa3Sdrh   pBlock = sqlite3DbMallocRawNN(pWInfo->pParse->db, nByte+sizeof(*pBlock));
261f8bdcfa3Sdrh   if( pBlock ){
262f8bdcfa3Sdrh     pBlock->pNext = pWInfo->pMemToFree;
263f8bdcfa3Sdrh     pBlock->sz = nByte;
264f8bdcfa3Sdrh     pWInfo->pMemToFree = pBlock;
265f8bdcfa3Sdrh     pBlock++;
266f8bdcfa3Sdrh   }
267f8bdcfa3Sdrh   return (void*)pBlock;
268f8bdcfa3Sdrh }
sqlite3WhereRealloc(WhereInfo * pWInfo,void * pOld,u64 nByte)269f8bdcfa3Sdrh void *sqlite3WhereRealloc(WhereInfo *pWInfo, void *pOld, u64 nByte){
270f8bdcfa3Sdrh   void *pNew = sqlite3WhereMalloc(pWInfo, nByte);
271f8bdcfa3Sdrh   if( pNew && pOld ){
272f8bdcfa3Sdrh     WhereMemBlock *pOldBlk = (WhereMemBlock*)pOld;
273f8bdcfa3Sdrh     pOldBlk--;
274f8bdcfa3Sdrh     assert( pOldBlk->sz<nByte );
275f8bdcfa3Sdrh     memcpy(pNew, pOld, pOldBlk->sz);
276f8bdcfa3Sdrh   }
277f8bdcfa3Sdrh   return pNew;
278f8bdcfa3Sdrh }
279f8bdcfa3Sdrh 
2806a3ea0e6Sdrh /*
2811398ad36Sdrh ** Create a new mask for cursor iCursor.
2820fcef5e1Sdrh **
2830fcef5e1Sdrh ** There is one cursor per table in the FROM clause.  The number of
2840fcef5e1Sdrh ** tables in the FROM clause is limited by a test early in the
285b6fb62d9Sdrh ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
2860fcef5e1Sdrh ** array will never overflow.
2871398ad36Sdrh */
createMask(WhereMaskSet * pMaskSet,int iCursor)288111a6a7dSdrh static void createMask(WhereMaskSet *pMaskSet, int iCursor){
289cad651e0Sdrh   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
2901398ad36Sdrh   pMaskSet->ix[pMaskSet->n++] = iCursor;
2911398ad36Sdrh }
2921398ad36Sdrh 
2931398ad36Sdrh /*
294235667a8Sdrh ** If the right-hand branch of the expression is a TK_COLUMN, then return
295235667a8Sdrh ** a pointer to the right-hand branch.  Otherwise, return NULL.
296235667a8Sdrh */
whereRightSubexprIsColumn(Expr * p)297235667a8Sdrh static Expr *whereRightSubexprIsColumn(Expr *p){
298235667a8Sdrh   p = sqlite3ExprSkipCollateAndLikely(p->pRight);
2999988db83Sdan   if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
3009988db83Sdan     return p;
3019988db83Sdan   }
302235667a8Sdrh   return 0;
303235667a8Sdrh }
304235667a8Sdrh 
305235667a8Sdrh /*
3061c8148ffSdrh ** Advance to the next WhereTerm that matches according to the criteria
3071c8148ffSdrh ** established when the pScan object was initialized by whereScanInit().
3081c8148ffSdrh ** Return NULL if there are no more matching WhereTerms.
3091c8148ffSdrh */
whereScanNext(WhereScan * pScan)310b2cfc146Sdan static WhereTerm *whereScanNext(WhereScan *pScan){
3111c8148ffSdrh   int iCur;            /* The cursor on the LHS of the term */
312a3f108e9Sdrh   i16 iColumn;         /* The column on the LHS of the term.  -1 for IPK */
3131c8148ffSdrh   Expr *pX;            /* An expression being tested */
3141c8148ffSdrh   WhereClause *pWC;    /* Shorthand for pScan->pWC */
3151c8148ffSdrh   WhereTerm *pTerm;    /* The term being tested */
31643b85ef5Sdrh   int k = pScan->k;    /* Where to start scanning */
3171c8148ffSdrh 
318392ddeb1Sdrh   assert( pScan->iEquiv<=pScan->nEquiv );
319392ddeb1Sdrh   pWC = pScan->pWC;
320392ddeb1Sdrh   while(1){
321a3f108e9Sdrh     iColumn = pScan->aiColumn[pScan->iEquiv-1];
322392ddeb1Sdrh     iCur = pScan->aiCur[pScan->iEquiv-1];
323392ddeb1Sdrh     assert( pWC!=0 );
324220f0d6fSdrh     assert( iCur>=0 );
325392ddeb1Sdrh     do{
32643b85ef5Sdrh       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
327220f0d6fSdrh         assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 || pTerm->leftCursor<0 );
328e1a086e4Sdrh         if( pTerm->leftCursor==iCur
32975fa2663Sdrh          && pTerm->u.x.leftColumn==iColumn
3304b92f98cSdrh          && (iColumn!=XN_EXPR
331f9463dfbSdrh              || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
332f9463dfbSdrh                                        pScan->pIdxExpr,iCur)==0)
33367a99dbeSdrh          && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON))
334e1a086e4Sdrh         ){
3351c8148ffSdrh           if( (pTerm->eOperator & WO_EQUIV)!=0
336a3f108e9Sdrh            && pScan->nEquiv<ArraySize(pScan->aiCur)
337235667a8Sdrh            && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
3381c8148ffSdrh           ){
3391c8148ffSdrh             int j;
340a3f108e9Sdrh             for(j=0; j<pScan->nEquiv; j++){
341a3f108e9Sdrh               if( pScan->aiCur[j]==pX->iTable
342a3f108e9Sdrh                && pScan->aiColumn[j]==pX->iColumn ){
3431c8148ffSdrh                   break;
3441c8148ffSdrh               }
3451c8148ffSdrh             }
3461c8148ffSdrh             if( j==pScan->nEquiv ){
347a3f108e9Sdrh               pScan->aiCur[j] = pX->iTable;
348a3f108e9Sdrh               pScan->aiColumn[j] = pX->iColumn;
349a3f108e9Sdrh               pScan->nEquiv++;
3501c8148ffSdrh             }
3511c8148ffSdrh           }
3521c8148ffSdrh           if( (pTerm->eOperator & pScan->opMask)!=0 ){
3531c8148ffSdrh             /* Verify the affinity and collating sequence match */
3541c8148ffSdrh             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
3551c8148ffSdrh               CollSeq *pColl;
35670d18344Sdrh               Parse *pParse = pWC->pWInfo->pParse;
3571c8148ffSdrh               pX = pTerm->pExpr;
3581c8148ffSdrh               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
3591c8148ffSdrh                 continue;
3601c8148ffSdrh               }
3611c8148ffSdrh               assert(pX->pLeft);
362898c527eSdrh               pColl = sqlite3ExprCompareCollSeq(pParse, pX);
36370d18344Sdrh               if( pColl==0 ) pColl = pParse->db->pDfltColl;
3641c8148ffSdrh               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
3651c8148ffSdrh                 continue;
3661c8148ffSdrh               }
3671c8148ffSdrh             }
368e8d0c61fSdrh             if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
369c59ffa8cSdrh              && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))
370c59ffa8cSdrh              && pX->op==TK_COLUMN
371a3f108e9Sdrh              && pX->iTable==pScan->aiCur[0]
372a3f108e9Sdrh              && pX->iColumn==pScan->aiColumn[0]
373a184fb87Sdrh             ){
374e8d0c61fSdrh               testcase( pTerm->eOperator & WO_IS );
375a184fb87Sdrh               continue;
376a184fb87Sdrh             }
377392ddeb1Sdrh             pScan->pWC = pWC;
37843b85ef5Sdrh             pScan->k = k+1;
3796068b6b4Sdrh #ifdef WHERETRACE_ENABLED
3806068b6b4Sdrh             if( sqlite3WhereTrace & 0x20000 ){
3816068b6b4Sdrh               int ii;
3826068b6b4Sdrh               sqlite3DebugPrintf("SCAN-TERM %p: nEquiv=%d",
3836068b6b4Sdrh                  pTerm, pScan->nEquiv);
3846068b6b4Sdrh               for(ii=0; ii<pScan->nEquiv; ii++){
3856068b6b4Sdrh                 sqlite3DebugPrintf(" {%d:%d}",
3866068b6b4Sdrh                    pScan->aiCur[ii], pScan->aiColumn[ii]);
3876068b6b4Sdrh               }
3886068b6b4Sdrh               sqlite3DebugPrintf("\n");
3896068b6b4Sdrh             }
3906068b6b4Sdrh #endif
3911c8148ffSdrh             return pTerm;
3921c8148ffSdrh           }
3931c8148ffSdrh         }
3941c8148ffSdrh       }
395392ddeb1Sdrh       pWC = pWC->pOuter;
39643b85ef5Sdrh       k = 0;
397392ddeb1Sdrh     }while( pWC!=0 );
398392ddeb1Sdrh     if( pScan->iEquiv>=pScan->nEquiv ) break;
399392ddeb1Sdrh     pWC = pScan->pOrigWC;
40043b85ef5Sdrh     k = 0;
401a3f108e9Sdrh     pScan->iEquiv++;
4021c8148ffSdrh   }
4031c8148ffSdrh   return 0;
4041c8148ffSdrh }
4051c8148ffSdrh 
4061c8148ffSdrh /*
407e86974c6Sdrh ** This is whereScanInit() for the case of an index on an expression.
408e86974c6Sdrh ** It is factored out into a separate tail-recursion subroutine so that
409e86974c6Sdrh ** the normal whereScanInit() routine, which is a high-runner, does not
410e86974c6Sdrh ** need to push registers onto the stack as part of its prologue.
411e86974c6Sdrh */
whereScanInitIndexExpr(WhereScan * pScan)412e86974c6Sdrh static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
413e86974c6Sdrh   pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
414e86974c6Sdrh   return whereScanNext(pScan);
415e86974c6Sdrh }
416e86974c6Sdrh 
417e86974c6Sdrh /*
4181c8148ffSdrh ** Initialize a WHERE clause scanner object.  Return a pointer to the
4191c8148ffSdrh ** first match.  Return NULL if there are no matches.
4201c8148ffSdrh **
4211c8148ffSdrh ** The scanner will be searching the WHERE clause pWC.  It will look
4221c8148ffSdrh ** for terms of the form "X <op> <expr>" where X is column iColumn of table
423a3fd75d4Sdrh ** iCur.   Or if pIdx!=0 then X is column iColumn of index pIdx.  pIdx
424a3fd75d4Sdrh ** must be one of the indexes of table iCur.
425a3fd75d4Sdrh **
426a3fd75d4Sdrh ** The <op> must be one of the operators described by opMask.
4271c8148ffSdrh **
4283b48e8c9Sdrh ** If the search is for X and the WHERE clause contains terms of the
4293b48e8c9Sdrh ** form X=Y then this routine might also return terms of the form
4303b48e8c9Sdrh ** "Y <op> <expr>".  The number of levels of transitivity is limited,
4313b48e8c9Sdrh ** but is enough to handle most commonly occurring SQL statements.
4323b48e8c9Sdrh **
4331c8148ffSdrh ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
4341c8148ffSdrh ** index pIdx.
4351c8148ffSdrh */
whereScanInit(WhereScan * pScan,WhereClause * pWC,int iCur,int iColumn,u32 opMask,Index * pIdx)436b2cfc146Sdan static WhereTerm *whereScanInit(
4371c8148ffSdrh   WhereScan *pScan,       /* The WhereScan object being initialized */
4381c8148ffSdrh   WhereClause *pWC,       /* The WHERE clause to be scanned */
4391c8148ffSdrh   int iCur,               /* Cursor to scan for */
4401c8148ffSdrh   int iColumn,            /* Column to scan for */
4411c8148ffSdrh   u32 opMask,             /* Operator(s) to scan for */
4421c8148ffSdrh   Index *pIdx             /* Must be compatible with this index */
4431c8148ffSdrh ){
4441c8148ffSdrh   pScan->pOrigWC = pWC;
4451c8148ffSdrh   pScan->pWC = pWC;
4466860e6faSdrh   pScan->pIdxExpr = 0;
447e9d935a8Sdrh   pScan->idxaff = 0;
448e9d935a8Sdrh   pScan->zCollName = 0;
449e86974c6Sdrh   pScan->opMask = opMask;
450e86974c6Sdrh   pScan->k = 0;
451e86974c6Sdrh   pScan->aiCur[0] = iCur;
452e86974c6Sdrh   pScan->nEquiv = 1;
453e86974c6Sdrh   pScan->iEquiv = 1;
4549904298bSdrh   if( pIdx ){
4559904298bSdrh     int j = iColumn;
4569904298bSdrh     iColumn = pIdx->aiColumn[j];
45779ab3841Sdrh     if( iColumn==pIdx->pTable->iPKey ){
4589904298bSdrh       iColumn = XN_ROWID;
4599904298bSdrh     }else if( iColumn>=0 ){
4609904298bSdrh       pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
4619904298bSdrh       pScan->zCollName = pIdx->azColl[j];
46279ab3841Sdrh     }else if( iColumn==XN_EXPR ){
46379ab3841Sdrh       pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
46479ab3841Sdrh       pScan->zCollName = pIdx->azColl[j];
46579ab3841Sdrh       pScan->aiColumn[0] = XN_EXPR;
46679ab3841Sdrh       return whereScanInitIndexExpr(pScan);
4679904298bSdrh     }
4689904298bSdrh   }else if( iColumn==XN_EXPR ){
4699904298bSdrh     return 0;
4701c8148ffSdrh   }
471a3f108e9Sdrh   pScan->aiColumn[0] = iColumn;
4721c8148ffSdrh   return whereScanNext(pScan);
4731c8148ffSdrh }
4741c8148ffSdrh 
4751c8148ffSdrh /*
476fe05af87Sdrh ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
477a3fd75d4Sdrh ** where X is a reference to the iColumn of table iCur or of index pIdx
478a3fd75d4Sdrh ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
479a3fd75d4Sdrh ** the op parameter.  Return a pointer to the term.  Return 0 if not found.
48058eb1c0aSdrh **
481a3fd75d4Sdrh ** If pIdx!=0 then it must be one of the indexes of table iCur.
482a3fd75d4Sdrh ** Search for terms matching the iColumn-th column of pIdx
483bb52308fSdrh ** rather than the iColumn-th column of table iCur.
484bb52308fSdrh **
48558eb1c0aSdrh ** The term returned might by Y=<expr> if there is another constraint in
48658eb1c0aSdrh ** the WHERE clause that specifies that X=Y.  Any such constraints will be
48758eb1c0aSdrh ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
488a3f108e9Sdrh ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
489a3f108e9Sdrh ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
490a3f108e9Sdrh ** other equivalent values.  Hence a search for X will return <expr> if X=A1
491a3f108e9Sdrh ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
49258eb1c0aSdrh **
49358eb1c0aSdrh ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
49458eb1c0aSdrh ** then try for the one with no dependencies on <expr> - in other words where
49558eb1c0aSdrh ** <expr> is a constant expression of some kind.  Only return entries of
49658eb1c0aSdrh ** the form "X <op> Y" where Y is a column in another table if no terms of
497459f63e7Sdrh ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
498459f63e7Sdrh ** exist, try to return a term that does not use WO_EQUIV.
499fe05af87Sdrh */
sqlite3WhereFindTerm(WhereClause * pWC,int iCur,int iColumn,Bitmask notReady,u32 op,Index * pIdx)5006f82e85aSdrh WhereTerm *sqlite3WhereFindTerm(
501fe05af87Sdrh   WhereClause *pWC,     /* The WHERE clause to be searched */
502fe05af87Sdrh   int iCur,             /* Cursor number of LHS */
503fe05af87Sdrh   int iColumn,          /* Column number of LHS */
504fe05af87Sdrh   Bitmask notReady,     /* RHS must not overlap with this mask */
505ec1724e8Sdrh   u32 op,               /* Mask of WO_xx values describing operator */
506fe05af87Sdrh   Index *pIdx           /* Must be compatible with this index, if not NULL */
507fe05af87Sdrh ){
5081c8148ffSdrh   WhereTerm *pResult = 0;
5091c8148ffSdrh   WhereTerm *p;
5101c8148ffSdrh   WhereScan scan;
5117a5bcc0fSdrh 
5121c8148ffSdrh   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
513e8d0c61fSdrh   op &= WO_EQ|WO_IS;
5141c8148ffSdrh   while( p ){
5151c8148ffSdrh     if( (p->prereqRight & notReady)==0 ){
516e8d0c61fSdrh       if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
517e8d0c61fSdrh         testcase( p->eOperator & WO_IS );
5181c8148ffSdrh         return p;
51963db0392Sdrh       }
5201c8148ffSdrh       if( pResult==0 ) pResult = p;
52122c2403aSdrh     }
5221c8148ffSdrh     p = whereScanNext(&scan);
52363db0392Sdrh   }
5247a5bcc0fSdrh   return pResult;
525fe05af87Sdrh }
526fe05af87Sdrh 
5277b4fc6a8Sdrh /*
52860ec914cSpeter.d.reid ** This function searches pList for an entry that matches the iCol-th column
5293b48e8c9Sdrh ** of index pIdx.
5306f343969Sdan **
5316f343969Sdan ** If such an expression is found, its index in pList->a[] is returned. If
5326f343969Sdan ** no expression is found, -1 is returned.
5336f343969Sdan */
findIndexCol(Parse * pParse,ExprList * pList,int iBase,Index * pIdx,int iCol)5346f343969Sdan static int findIndexCol(
5356f343969Sdan   Parse *pParse,                  /* Parse context */
5366f343969Sdan   ExprList *pList,                /* Expression list to search */
5376f343969Sdan   int iBase,                      /* Cursor for table associated with pIdx */
5386f343969Sdan   Index *pIdx,                    /* Index to match column of */
5396f343969Sdan   int iCol                        /* Column of index to match */
5406f343969Sdan ){
5416f343969Sdan   int i;
5426f343969Sdan   const char *zColl = pIdx->azColl[iCol];
5436f343969Sdan 
5446f343969Sdan   for(i=0; i<pList->nExpr; i++){
5450d950af3Sdrh     Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
546235667a8Sdrh     if( ALWAYS(p!=0)
5474fcb30b7Sdan      && (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)
548f1d3e329Sdrh      && p->iColumn==pIdx->aiColumn[iCol]
549f1d3e329Sdrh      && p->iTable==iBase
550f1d3e329Sdrh     ){
55170efa84dSdrh       CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
55270efa84dSdrh       if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
5536f343969Sdan         return i;
5546f343969Sdan       }
5556f343969Sdan     }
5566f343969Sdan   }
5576f343969Sdan 
5586f343969Sdan   return -1;
5596f343969Sdan }
5606f343969Sdan 
5616f343969Sdan /*
562bb52308fSdrh ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
563bb52308fSdrh */
indexColumnNotNull(Index * pIdx,int iCol)564bb52308fSdrh static int indexColumnNotNull(Index *pIdx, int iCol){
565bb52308fSdrh   int j;
566bb52308fSdrh   assert( pIdx!=0 );
567bb52308fSdrh   assert( iCol>=0 && iCol<pIdx->nColumn );
568bb52308fSdrh   j = pIdx->aiColumn[iCol];
569bb52308fSdrh   if( j>=0 ){
570bb52308fSdrh     return pIdx->pTable->aCol[j].notNull;
571bb52308fSdrh   }else if( j==(-1) ){
572bb52308fSdrh     return 1;
573bb52308fSdrh   }else{
574bb52308fSdrh     assert( j==(-2) );
5758492653cSdrh     return 0;  /* Assume an indexed expression can always yield a NULL */
5767d3d9daeSdrh 
577bb52308fSdrh   }
578bb52308fSdrh }
579bb52308fSdrh 
580bb52308fSdrh /*
5816f343969Sdan ** Return true if the DISTINCT expression-list passed as the third argument
5824f402f26Sdrh ** is redundant.
5834f402f26Sdrh **
584b121dd14Sdrh ** A DISTINCT list is redundant if any subset of the columns in the
585b121dd14Sdrh ** DISTINCT list are collectively unique and individually non-null.
5866f343969Sdan */
isDistinctRedundant(Parse * pParse,SrcList * pTabList,WhereClause * pWC,ExprList * pDistinct)5876f343969Sdan static int isDistinctRedundant(
5884f402f26Sdrh   Parse *pParse,            /* Parsing context */
5894f402f26Sdrh   SrcList *pTabList,        /* The FROM clause */
5904f402f26Sdrh   WhereClause *pWC,         /* The WHERE clause */
5914f402f26Sdrh   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
5926f343969Sdan ){
5936f343969Sdan   Table *pTab;
5946f343969Sdan   Index *pIdx;
5956f343969Sdan   int i;
5966f343969Sdan   int iBase;
5976f343969Sdan 
5986f343969Sdan   /* If there is more than one table or sub-select in the FROM clause of
5996f343969Sdan   ** this query, then it will not be possible to show that the DISTINCT
6006f343969Sdan   ** clause is redundant. */
6016f343969Sdan   if( pTabList->nSrc!=1 ) return 0;
6026f343969Sdan   iBase = pTabList->a[0].iCursor;
6036f343969Sdan   pTab = pTabList->a[0].pTab;
6046f343969Sdan 
60594e08d92Sdan   /* If any of the expressions is an IPK column on table iBase, then return
60694e08d92Sdan   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
60794e08d92Sdan   ** current SELECT is a correlated sub-query.
60894e08d92Sdan   */
6096f343969Sdan   for(i=0; i<pDistinct->nExpr; i++){
6100d950af3Sdrh     Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);
611235667a8Sdrh     if( NEVER(p==0) ) continue;
6124fcb30b7Sdan     if( p->op!=TK_COLUMN && p->op!=TK_AGG_COLUMN ) continue;
6134fcb30b7Sdan     if( p->iTable==iBase && p->iColumn<0 ) return 1;
6146f343969Sdan   }
6156f343969Sdan 
6166f343969Sdan   /* Loop through all indices on the table, checking each to see if it makes
6176f343969Sdan   ** the DISTINCT qualifier redundant. It does so if:
6186f343969Sdan   **
6196f343969Sdan   **   1. The index is itself UNIQUE, and
6206f343969Sdan   **
6216f343969Sdan   **   2. All of the columns in the index are either part of the pDistinct
6226f343969Sdan   **      list, or else the WHERE clause contains a term of the form "col=X",
6236f343969Sdan   **      where X is a constant value. The collation sequences of the
6246f343969Sdan   **      comparison and select-list expressions must match those of the index.
6256a36f435Sdan   **
6266a36f435Sdan   **   3. All of those index columns for which the WHERE clause does not
6276a36f435Sdan   **      contain a "col=X" term are subject to a NOT NULL constraint.
6286f343969Sdan   */
6296f343969Sdan   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
6305f1d1d9cSdrh     if( !IsUniqueIndex(pIdx) ) continue;
631204b6342Sdrh     if( pIdx->pPartIdxWhere ) continue;
632bbbdc83bSdrh     for(i=0; i<pIdx->nKeyCol; i++){
633bb52308fSdrh       if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
634bb52308fSdrh         if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
635bb52308fSdrh         if( indexColumnNotNull(pIdx, i)==0 ) break;
6366f343969Sdan       }
6376a36f435Sdan     }
638bbbdc83bSdrh     if( i==pIdx->nKeyCol ){
6396f343969Sdan       /* This index implies that the DISTINCT qualifier is redundant. */
6406f343969Sdan       return 1;
6416f343969Sdan     }
6426f343969Sdan   }
6436f343969Sdan 
6446f343969Sdan   return 0;
6456f343969Sdan }
64675897234Sdrh 
6478636e9c5Sdrh 
648b8a8e8a5Sdrh /*
6493b48e8c9Sdrh ** Estimate the logarithm of the input value to base 2.
65028c4cf42Sdrh */
estLog(LogEst N)651bf539c4dSdrh static LogEst estLog(LogEst N){
652696964d0Sdrh   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
65328c4cf42Sdrh }
65428c4cf42Sdrh 
6556d209d8bSdrh /*
6567b3aa08eSdrh ** Convert OP_Column opcodes to OP_Copy in previously generated code.
6577b3aa08eSdrh **
6587b3aa08eSdrh ** This routine runs over generated VDBE code and translates OP_Column
659fb785b2cSdan ** opcodes into OP_Copy when the table is being accessed via co-routine
660fb785b2cSdan ** instead of via table lookup.
661fb785b2cSdan **
66200a6153fSdrh ** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
66300a6153fSdrh ** cursor iTabCur are transformed into OP_Sequence opcode for the
66400a6153fSdrh ** iAutoidxCur cursor, in order to generate unique rowids for the
66500a6153fSdrh ** automatic index being generated.
6667b3aa08eSdrh */
translateColumnToCopy(Parse * pParse,int iStart,int iTabCur,int iRegister,int iAutoidxCur)6677b3aa08eSdrh static void translateColumnToCopy(
668202230efSdrh   Parse *pParse,      /* Parsing context */
6697b3aa08eSdrh   int iStart,         /* Translate from this opcode to the end */
6707b3aa08eSdrh   int iTabCur,        /* OP_Column/OP_Rowid references to this table */
671fb785b2cSdan   int iRegister,      /* The first column is in this register */
67200a6153fSdrh   int iAutoidxCur     /* If non-zero, cursor of autoindex being generated */
6737b3aa08eSdrh ){
674202230efSdrh   Vdbe *v = pParse->pVdbe;
6757b3aa08eSdrh   VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
6767b3aa08eSdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
677202230efSdrh   if( pParse->db->mallocFailed ) return;
6787b3aa08eSdrh   for(; iStart<iEnd; iStart++, pOp++){
6797b3aa08eSdrh     if( pOp->p1!=iTabCur ) continue;
6807b3aa08eSdrh     if( pOp->opcode==OP_Column ){
6817b3aa08eSdrh       pOp->opcode = OP_Copy;
6827b3aa08eSdrh       pOp->p1 = pOp->p2 + iRegister;
6837b3aa08eSdrh       pOp->p2 = pOp->p3;
6847b3aa08eSdrh       pOp->p3 = 0;
685e5dea284Sdrh       pOp->p5 = 2;  /* Cause the MEM_Subtype flag to be cleared */
6867b3aa08eSdrh     }else if( pOp->opcode==OP_Rowid ){
68700a6153fSdrh       pOp->opcode = OP_Sequence;
68800a6153fSdrh       pOp->p1 = iAutoidxCur;
6896e5020e8Sdrh #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
6906e5020e8Sdrh       if( iAutoidxCur==0 ){
6917b3aa08eSdrh         pOp->opcode = OP_Null;
6927b3aa08eSdrh         pOp->p3 = 0;
6937b3aa08eSdrh       }
6946e5020e8Sdrh #endif
6957b3aa08eSdrh     }
6967b3aa08eSdrh   }
697fb785b2cSdan }
6987b3aa08eSdrh 
6997b3aa08eSdrh /*
7006d209d8bSdrh ** Two routines for printing the content of an sqlite3_index_info
7016d209d8bSdrh ** structure.  Used for testing and debugging only.  If neither
7026d209d8bSdrh ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
7036d209d8bSdrh ** are no-ops.
7046d209d8bSdrh */
705d15cb171Sdrh #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
whereTraceIndexInfoInputs(sqlite3_index_info * p)706cfcf4de4Sdrh static void whereTraceIndexInfoInputs(sqlite3_index_info *p){
7076d209d8bSdrh   int i;
7083a00f907Smlcreech   if( !sqlite3WhereTrace ) return;
7096d209d8bSdrh   for(i=0; i<p->nConstraint; i++){
710b6592f65Sdrh     sqlite3DebugPrintf(
711b6592f65Sdrh        "  constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n",
7126d209d8bSdrh        i,
7136d209d8bSdrh        p->aConstraint[i].iColumn,
7146d209d8bSdrh        p->aConstraint[i].iTermOffset,
7156d209d8bSdrh        p->aConstraint[i].op,
716b6592f65Sdrh        p->aConstraint[i].usable,
717b6592f65Sdrh        sqlite3_vtab_collation(p,i));
7186d209d8bSdrh   }
7196d209d8bSdrh   for(i=0; i<p->nOrderBy; i++){
7206d209d8bSdrh     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
7216d209d8bSdrh        i,
7226d209d8bSdrh        p->aOrderBy[i].iColumn,
7236d209d8bSdrh        p->aOrderBy[i].desc);
7246d209d8bSdrh   }
7256d209d8bSdrh }
whereTraceIndexInfoOutputs(sqlite3_index_info * p)726cfcf4de4Sdrh static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){
7276d209d8bSdrh   int i;
7283a00f907Smlcreech   if( !sqlite3WhereTrace ) return;
7296d209d8bSdrh   for(i=0; i<p->nConstraint; i++){
7306d209d8bSdrh     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
7316d209d8bSdrh        i,
7326d209d8bSdrh        p->aConstraintUsage[i].argvIndex,
7336d209d8bSdrh        p->aConstraintUsage[i].omit);
7346d209d8bSdrh   }
7356d209d8bSdrh   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
7366d209d8bSdrh   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
7376d209d8bSdrh   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
7386d209d8bSdrh   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
739a9f5815bSdan   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
7406d209d8bSdrh }
7416d209d8bSdrh #else
742cfcf4de4Sdrh #define whereTraceIndexInfoInputs(A)
743cfcf4de4Sdrh #define whereTraceIndexInfoOutputs(A)
7446d209d8bSdrh #endif
7456d209d8bSdrh 
746faaacd3fSdrh /*
747faaacd3fSdrh ** We know that pSrc is an operand of an outer join.  Return true if
748faaacd3fSdrh ** pTerm is a constraint that is compatible with that join.
749faaacd3fSdrh **
750faaacd3fSdrh ** pTerm must be EP_OuterON if pSrc is the right operand of an
751faaacd3fSdrh ** outer join.  pTerm can be either EP_OuterON or EP_InnerON if pSrc
752faaacd3fSdrh ** is the left operand of a RIGHT join.
753f333370eSdrh **
754f333370eSdrh ** See https://sqlite.org/forum/forumpost/206d99a16dd9212f
755f333370eSdrh ** for an example of a WHERE clause constraints that may not be used on
756f333370eSdrh ** the right table of a RIGHT JOIN because the constraint implies a
757f333370eSdrh ** not-NULL condition on the left table of the RIGHT JOIN.
758faaacd3fSdrh */
constraintCompatibleWithOuterJoin(const WhereTerm * pTerm,const SrcItem * pSrc)759faaacd3fSdrh static int constraintCompatibleWithOuterJoin(
760faaacd3fSdrh   const WhereTerm *pTerm,       /* WHERE clause term to check */
761faaacd3fSdrh   const SrcItem *pSrc           /* Table we are trying to access */
762faaacd3fSdrh ){
763faaacd3fSdrh   assert( (pSrc->fg.jointype&(JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 ); /* By caller */
764faaacd3fSdrh   testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LEFT );
765faaacd3fSdrh   testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LTORJ );
766faaacd3fSdrh   testcase( ExprHasProperty(pTerm->pExpr, EP_OuterON) )
767faaacd3fSdrh   testcase( ExprHasProperty(pTerm->pExpr, EP_InnerON) );
768faaacd3fSdrh   if( !ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON)
769faaacd3fSdrh    || pTerm->pExpr->w.iJoin != pSrc->iCursor
770faaacd3fSdrh   ){
771faaacd3fSdrh     return 0;
772faaacd3fSdrh   }
773faaacd3fSdrh   if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0
774faaacd3fSdrh    && ExprHasProperty(pTerm->pExpr, EP_InnerON)
775faaacd3fSdrh   ){
776faaacd3fSdrh     return 0;
777faaacd3fSdrh   }
778faaacd3fSdrh   return 1;
779faaacd3fSdrh }
780faaacd3fSdrh 
781faaacd3fSdrh 
782faaacd3fSdrh 
783c6339081Sdrh #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
7848b307fbfSdrh /*
7854139c99eSdrh ** Return TRUE if the WHERE clause term pTerm is of a form where it
7864139c99eSdrh ** could be used with an index to access pSrc, assuming an appropriate
7874139c99eSdrh ** index existed.
7884139c99eSdrh */
termCanDriveIndex(const WhereTerm * pTerm,const SrcItem * pSrc,const Bitmask notReady)7894139c99eSdrh static int termCanDriveIndex(
790fecbf0a1Sdrh   const WhereTerm *pTerm,        /* WHERE clause term to check */
791fecbf0a1Sdrh   const SrcItem *pSrc,           /* Table we are trying to access */
792fecbf0a1Sdrh   const Bitmask notReady         /* Tables in outer loops of the join */
7934139c99eSdrh ){
7944139c99eSdrh   char aff;
7954139c99eSdrh   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
796e8d0c61fSdrh   if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
7971cc5c4acSdrh   assert( (pSrc->fg.jointype & JT_RIGHT)==0 );
798faaacd3fSdrh   if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
799faaacd3fSdrh    && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
800bbccd521Sdan   ){
801f333370eSdrh     return 0;  /* See https://sqlite.org/forum/forumpost/51e6959f61 */
802bbccd521Sdan   }
8034139c99eSdrh   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
804220f0d6fSdrh   assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
80575fa2663Sdrh   if( pTerm->u.x.leftColumn<0 ) return 0;
80675fa2663Sdrh   aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
8074139c99eSdrh   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
808e0cc3c29Sdrh   testcase( pTerm->pExpr->op==TK_IS );
8094139c99eSdrh   return 1;
8104139c99eSdrh }
811c6339081Sdrh #endif
8124139c99eSdrh 
813c6339081Sdrh 
814c6339081Sdrh #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
8158b307fbfSdrh /*
816c6339081Sdrh ** Generate code to construct the Index object for an automatic index
817c6339081Sdrh ** and to set up the WhereLevel object pLevel so that the code generator
818c6339081Sdrh ** makes use of the automatic index.
8198b307fbfSdrh */
constructAutomaticIndex(Parse * pParse,const WhereClause * pWC,const SrcItem * pSrc,const Bitmask notReady,WhereLevel * pLevel)820fa35f5c5Sdrh static SQLITE_NOINLINE void constructAutomaticIndex(
8218b307fbfSdrh   Parse *pParse,              /* The parsing context */
822fecbf0a1Sdrh   const WhereClause *pWC,     /* The WHERE clause */
823fecbf0a1Sdrh   const SrcItem *pSrc,        /* The FROM clause term to get the next index */
824fecbf0a1Sdrh   const Bitmask notReady,     /* Mask of cursors that are not available */
8258b307fbfSdrh   WhereLevel *pLevel          /* Write new index here */
8268b307fbfSdrh ){
827bbbdc83bSdrh   int nKeyCol;                /* Number of columns in the constructed index */
8288b307fbfSdrh   WhereTerm *pTerm;           /* A single term of the WHERE clause */
8298b307fbfSdrh   WhereTerm *pWCEnd;          /* End of pWC->a[] */
8308b307fbfSdrh   Index *pIdx;                /* Object describing the transient index */
8318b307fbfSdrh   Vdbe *v;                    /* Prepared statement under construction */
8328b307fbfSdrh   int addrInit;               /* Address of the initialization bypass jump */
8338b307fbfSdrh   Table *pTable;              /* The table being indexed */
8348b307fbfSdrh   int addrTop;                /* Top of the index fill loop */
8358b307fbfSdrh   int regRecord;              /* Register holding an index record */
8368b307fbfSdrh   int n;                      /* Column counter */
8374139c99eSdrh   int i;                      /* Loop counter */
8384139c99eSdrh   int mxBitCol;               /* Maximum column in pSrc->colUsed */
839424aab88Sdrh   CollSeq *pColl;             /* Collating sequence to on a column */
8407ba39a92Sdrh   WhereLoop *pLoop;           /* The Loop object */
84177e57dfbSdrh   char *zNotUsed;             /* Extra space on the end of pIdx */
8424139c99eSdrh   Bitmask idxCols;            /* Bitmap of columns used for indexing */
8434139c99eSdrh   Bitmask extraCols;          /* Bitmap of additional columns */
8448d56e205Sdrh   u8 sentWarning = 0;         /* True if a warnning has been issued */
845059b2d50Sdrh   Expr *pPartial = 0;         /* Partial Index Expression */
846059b2d50Sdrh   int iContinue = 0;          /* Jump here to skip excluded rows */
8477601294aSdrh   SrcItem *pTabItem;          /* FROM clause term being indexed */
8484dd83a22Sdrh   int addrCounter = 0;        /* Address where integer counter is initialized */
849fb785b2cSdan   int regBase;                /* Array of registers where record is assembled */
8508b307fbfSdrh 
8518b307fbfSdrh   /* Generate code to skip over the creation and initialization of the
8528b307fbfSdrh   ** transient index on 2nd and subsequent iterations of the loop. */
8538b307fbfSdrh   v = pParse->pVdbe;
8548b307fbfSdrh   assert( v!=0 );
855511f9e8dSdrh   addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
8568b307fbfSdrh 
8574139c99eSdrh   /* Count the number of columns that will be added to the index
8584139c99eSdrh   ** and used to match WHERE clause constraints */
859bbbdc83bSdrh   nKeyCol = 0;
860424aab88Sdrh   pTable = pSrc->pTab;
8618b307fbfSdrh   pWCEnd = &pWC->a[pWC->nTerm];
8627ba39a92Sdrh   pLoop = pLevel->pWLoop;
8634139c99eSdrh   idxCols = 0;
86481186b43Sdrh   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
86513cc90cfSdrh     Expr *pExpr = pTerm->pExpr;
866c1085ea4Sdrh     /* Make the automatic index a partial index if there are terms in the
867c1085ea4Sdrh     ** WHERE clause (or the ON clause of a LEFT join) that constrain which
868c1085ea4Sdrh     ** rows of the target table (pSrc) that can be used. */
869c1085ea4Sdrh     if( (pTerm->wtFlags & TERM_VIRTUAL)==0
870a9cdb904Sdrh      && sqlite3ExprIsTableConstraint(pExpr, pSrc)
871c1085ea4Sdrh     ){
872d5c851c1Sdrh       pPartial = sqlite3ExprAnd(pParse, pPartial,
87313cc90cfSdrh                                 sqlite3ExprDup(pParse->db, pExpr, 0));
874059b2d50Sdrh     }
8754139c99eSdrh     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
876220f0d6fSdrh       int iCol;
877220f0d6fSdrh       Bitmask cMask;
878220f0d6fSdrh       assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
879220f0d6fSdrh       iCol = pTerm->u.x.leftColumn;
880220f0d6fSdrh       cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
88152ff8ea6Sdrh       testcase( iCol==BMS );
88252ff8ea6Sdrh       testcase( iCol==BMS-1 );
8838d56e205Sdrh       if( !sentWarning ){
8848d56e205Sdrh         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
8858d56e205Sdrh             "automatic index on %s(%s)", pTable->zName,
886cf9d36d1Sdrh             pTable->aCol[iCol].zCnName);
8878d56e205Sdrh         sentWarning = 1;
8888d56e205Sdrh       }
8890013e72eSdrh       if( (idxCols & cMask)==0 ){
890059b2d50Sdrh         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
891059b2d50Sdrh           goto end_auto_index_create;
892059b2d50Sdrh         }
893bbbdc83bSdrh         pLoop->aLTerm[nKeyCol++] = pTerm;
8940013e72eSdrh         idxCols |= cMask;
8950013e72eSdrh       }
8968b307fbfSdrh     }
8978b307fbfSdrh   }
898d6a33de7Sdrh   assert( nKeyCol>0 || pParse->db->mallocFailed );
899bbbdc83bSdrh   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
90053b52f7fSdrh   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
901986b3879Sdrh                      | WHERE_AUTO_INDEX;
9024139c99eSdrh 
9034139c99eSdrh   /* Count the number of additional columns needed to create a
9044139c99eSdrh   ** covering index.  A "covering index" is an index that contains all
9054139c99eSdrh   ** columns that are needed by the query.  With a covering index, the
9064139c99eSdrh   ** original table never needs to be accessed.  Automatic indices must
9074139c99eSdrh   ** be a covering index because the index will not be updated if the
9084139c99eSdrh   ** original table changes and the index and table cannot both be used
9094139c99eSdrh   ** if they go out of sync.
9104139c99eSdrh   */
9117699d1c4Sdrh   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
912c3ef4fa8Sdrh   mxBitCol = MIN(BMS-1,pTable->nCol);
91352ff8ea6Sdrh   testcase( pTable->nCol==BMS-1 );
91452ff8ea6Sdrh   testcase( pTable->nCol==BMS-2 );
9154139c99eSdrh   for(i=0; i<mxBitCol; i++){
916bbbdc83bSdrh     if( extraCols & MASKBIT(i) ) nKeyCol++;
9174139c99eSdrh   }
9187699d1c4Sdrh   if( pSrc->colUsed & MASKBIT(BMS-1) ){
919bbbdc83bSdrh     nKeyCol += pTable->nCol - BMS + 1;
9204139c99eSdrh   }
9218b307fbfSdrh 
9228b307fbfSdrh   /* Construct the Index object to describe this index */
923bbbdc83bSdrh   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
924059b2d50Sdrh   if( pIdx==0 ) goto end_auto_index_create;
9257ba39a92Sdrh   pLoop->u.btree.pIndex = pIdx;
9268b307fbfSdrh   pIdx->zName = "auto-index";
927424aab88Sdrh   pIdx->pTable = pTable;
9288b307fbfSdrh   n = 0;
9290013e72eSdrh   idxCols = 0;
9308b307fbfSdrh   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
9314139c99eSdrh     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
932220f0d6fSdrh       int iCol;
933220f0d6fSdrh       Bitmask cMask;
934220f0d6fSdrh       assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
935220f0d6fSdrh       iCol = pTerm->u.x.leftColumn;
936220f0d6fSdrh       cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
9377963b0e8Sdrh       testcase( iCol==BMS-1 );
9387963b0e8Sdrh       testcase( iCol==BMS );
9390013e72eSdrh       if( (idxCols & cMask)==0 ){
9404139c99eSdrh         Expr *pX = pTerm->pExpr;
9410013e72eSdrh         idxCols |= cMask;
94275fa2663Sdrh         pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
943898c527eSdrh         pColl = sqlite3ExprCompareCollSeq(pParse, pX);
94434da2a48Sdrh         assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
94534da2a48Sdrh         pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
9468b307fbfSdrh         n++;
9478b307fbfSdrh       }
9488b307fbfSdrh     }
9490013e72eSdrh   }
9507ba39a92Sdrh   assert( (u32)n==pLoop->u.btree.nEq );
9514139c99eSdrh 
952c6339081Sdrh   /* Add additional columns needed to make the automatic index into
953c6339081Sdrh   ** a covering index */
9544139c99eSdrh   for(i=0; i<mxBitCol; i++){
9557699d1c4Sdrh     if( extraCols & MASKBIT(i) ){
9564139c99eSdrh       pIdx->aiColumn[n] = i;
957f19aa5faSdrh       pIdx->azColl[n] = sqlite3StrBINARY;
9584139c99eSdrh       n++;
9594139c99eSdrh     }
9604139c99eSdrh   }
9617699d1c4Sdrh   if( pSrc->colUsed & MASKBIT(BMS-1) ){
9624139c99eSdrh     for(i=BMS-1; i<pTable->nCol; i++){
9634139c99eSdrh       pIdx->aiColumn[n] = i;
964f19aa5faSdrh       pIdx->azColl[n] = sqlite3StrBINARY;
9654139c99eSdrh       n++;
9664139c99eSdrh     }
9674139c99eSdrh   }
968bbbdc83bSdrh   assert( n==nKeyCol );
9694b92f98cSdrh   pIdx->aiColumn[n] = XN_ROWID;
970f19aa5faSdrh   pIdx->azColl[n] = sqlite3StrBINARY;
9718b307fbfSdrh 
972c6339081Sdrh   /* Create the automatic index */
9738b307fbfSdrh   assert( pLevel->iIdxCur>=0 );
974a1f4124cSdrh   pLevel->iIdxCur = pParse->nTab++;
9752ec2fb22Sdrh   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
9762ec2fb22Sdrh   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
977a21a64ddSdrh   VdbeComment((v, "for %s", pTable->zName));
9782db144c3Sdrh   if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) ){
9792db144c3Sdrh     pLevel->regFilter = ++pParse->nMem;
98050fb7e09Sdrh     sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
9812db144c3Sdrh   }
9828b307fbfSdrh 
983c6339081Sdrh   /* Fill the automatic index with content */
9847b3aa08eSdrh   pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
9858a48b9c0Sdrh   if( pTabItem->fg.viaCoroutine ){
9867b3aa08eSdrh     int regYield = pTabItem->regReturn;
987fb785b2cSdan     addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
9887b3aa08eSdrh     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
9897b3aa08eSdrh     addrTop =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
9907b3aa08eSdrh     VdbeCoverage(v);
991fef37760Sdrh     VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
9927b3aa08eSdrh   }else{
993688852abSdrh     addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
9947b3aa08eSdrh   }
995059b2d50Sdrh   if( pPartial ){
996ec4ccdbcSdrh     iContinue = sqlite3VdbeMakeLabel(pParse);
997059b2d50Sdrh     sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
998051575cbSdrh     pLoop->wsFlags |= WHERE_PARTIALIDX;
999059b2d50Sdrh   }
10008b307fbfSdrh   regRecord = sqlite3GetTempReg(pParse);
1001fb785b2cSdan   regBase = sqlite3GenerateIndexKey(
1002fb785b2cSdan       pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
1003fb785b2cSdan   );
10042db144c3Sdrh   if( pLevel->regFilter ){
10052db144c3Sdrh     sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
10062db144c3Sdrh                          regBase, pLoop->u.btree.nEq);
10072db144c3Sdrh   }
10088b307fbfSdrh   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
10098b307fbfSdrh   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1010059b2d50Sdrh   if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
10118a48b9c0Sdrh   if( pTabItem->fg.viaCoroutine ){
1012fb785b2cSdan     sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
1013202230efSdrh     testcase( pParse->db->mallocFailed );
101400a6153fSdrh     assert( pLevel->iIdxCur>0 );
1015202230efSdrh     translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
101600a6153fSdrh                           pTabItem->regResult, pLevel->iIdxCur);
1017076e85f5Sdrh     sqlite3VdbeGoto(v, addrTop);
10182c04131cSdrh     pTabItem->fg.viaCoroutine = 0;
10197b3aa08eSdrh   }else{
1020688852abSdrh     sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
1021a21a64ddSdrh     sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
1022d9670abbSdrh   }
10238b307fbfSdrh   sqlite3VdbeJumpHere(v, addrTop);
10248b307fbfSdrh   sqlite3ReleaseTempReg(pParse, regRecord);
10258b307fbfSdrh 
10268b307fbfSdrh   /* Jump here when skipping the initialization */
10278b307fbfSdrh   sqlite3VdbeJumpHere(v, addrInit);
1028059b2d50Sdrh 
1029059b2d50Sdrh end_auto_index_create:
1030059b2d50Sdrh   sqlite3ExprDelete(pParse->db, pPartial);
10318b307fbfSdrh }
1032c6339081Sdrh #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
10338b307fbfSdrh 
1034fa35f5c5Sdrh /*
10356ae49e67Sdrh ** Generate bytecode that will initialize a Bloom filter that is appropriate
10366ae49e67Sdrh ** for pLevel.
10376ae49e67Sdrh **
10386ae49e67Sdrh ** If there are inner loops within pLevel that have the WHERE_BLOOMFILTER
10396ae49e67Sdrh ** flag set, initialize a Bloomfilter for them as well.  Except don't do
10406ae49e67Sdrh ** this recursive initialization if the SQLITE_BloomPulldown optimization has
10416ae49e67Sdrh ** been turned off.
10426ae49e67Sdrh **
10436ae49e67Sdrh ** When the Bloom filter is initialized, the WHERE_BLOOMFILTER flag is cleared
10446ae49e67Sdrh ** from the loop, but the regFilter value is set to a register that implements
10456ae49e67Sdrh ** the Bloom filter.  When regFilter is positive, the
10466ae49e67Sdrh ** sqlite3WhereCodeOneLoopStart() will generate code to test the Bloom filter
10476ae49e67Sdrh ** and skip the subsequence B-Tree seek if the Bloom filter indicates that
10486ae49e67Sdrh ** no matching rows exist.
10496ae49e67Sdrh **
10506ae49e67Sdrh ** This routine may only be called if it has previously been determined that
10516ae49e67Sdrh ** the loop would benefit from a Bloom filter, and the WHERE_BLOOMFILTER bit
10526ae49e67Sdrh ** is set.
1053fa35f5c5Sdrh */
sqlite3ConstructBloomFilter(WhereInfo * pWInfo,int iLevel,WhereLevel * pLevel,Bitmask notReady)105427a9e1f6Sdrh static SQLITE_NOINLINE void sqlite3ConstructBloomFilter(
10556ae49e67Sdrh   WhereInfo *pWInfo,    /* The WHERE clause */
10566ae49e67Sdrh   int iLevel,           /* Index in pWInfo->a[] that is pLevel */
1057761d64b7Sdrh   WhereLevel *pLevel,   /* Make a Bloom filter for this FROM term */
1058761d64b7Sdrh   Bitmask notReady      /* Loops that are not ready */
1059fa35f5c5Sdrh ){
10606ae49e67Sdrh   int addrOnce;                        /* Address of opening OP_Once */
10616ae49e67Sdrh   int addrTop;                         /* Address of OP_Rewind */
10626ae49e67Sdrh   int addrCont;                        /* Jump here to skip a row */
10636ae49e67Sdrh   const WhereTerm *pTerm;              /* For looping over WHERE clause terms */
10646ae49e67Sdrh   const WhereTerm *pWCEnd;             /* Last WHERE clause term */
10656ae49e67Sdrh   Parse *pParse = pWInfo->pParse;      /* Parsing context */
10666ae49e67Sdrh   Vdbe *v = pParse->pVdbe;             /* VDBE under construction */
10676ae49e67Sdrh   WhereLoop *pLoop = pLevel->pWLoop;   /* The loop being coded */
10686ae49e67Sdrh   int iCur;                            /* Cursor for table getting the filter */
1069fa35f5c5Sdrh 
1070fa35f5c5Sdrh   assert( pLoop!=0 );
1071fa35f5c5Sdrh   assert( v!=0 );
10726ae49e67Sdrh   assert( pLoop->wsFlags & WHERE_BLOOMFILTER );
10736ae49e67Sdrh 
10746ae49e67Sdrh   addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
10756ae49e67Sdrh   do{
107650fb7e09Sdrh     const SrcItem *pItem;
107750fb7e09Sdrh     const Table *pTab;
10787e910f64Sdrh     u64 sz;
10796ae49e67Sdrh     sqlite3WhereExplainBloomFilter(pParse, pWInfo, pLevel);
1080fa35f5c5Sdrh     addrCont = sqlite3VdbeMakeLabel(pParse);
10816ae49e67Sdrh     iCur = pLevel->iTabCur;
1082fa35f5c5Sdrh     pLevel->regFilter = ++pParse->nMem;
108350fb7e09Sdrh 
108450fb7e09Sdrh     /* The Bloom filter is a Blob held in a register.  Initialize it
108550fb7e09Sdrh     ** to zero-filled blob of at least 80K bits, but maybe more if the
108650fb7e09Sdrh     ** estimated size of the table is larger.  We could actually
108750fb7e09Sdrh     ** measure the size of the table at run-time using OP_Count with
108850fb7e09Sdrh     ** P3==1 and use that value to initialize the blob.  But that makes
108950fb7e09Sdrh     ** testing complicated.  By basing the blob size on the value in the
109050fb7e09Sdrh     ** sqlite_stat1 table, testing is much easier.
109150fb7e09Sdrh     */
109250fb7e09Sdrh     pItem = &pWInfo->pTabList->a[pLevel->iFrom];
109350fb7e09Sdrh     assert( pItem!=0 );
109450fb7e09Sdrh     pTab = pItem->pTab;
109550fb7e09Sdrh     assert( pTab!=0 );
10967e910f64Sdrh     sz = sqlite3LogEstToInt(pTab->nRowLogEst);
109750fb7e09Sdrh     if( sz<10000 ){
109850fb7e09Sdrh       sz = 10000;
109950fb7e09Sdrh     }else if( sz>10000000 ){
110050fb7e09Sdrh       sz = 10000000;
110150fb7e09Sdrh     }
11027e910f64Sdrh     sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
110350fb7e09Sdrh 
11046ae49e67Sdrh     addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
1105fa35f5c5Sdrh     pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
1106fa35f5c5Sdrh     for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
1107fa35f5c5Sdrh       Expr *pExpr = pTerm->pExpr;
1108fa35f5c5Sdrh       if( (pTerm->wtFlags & TERM_VIRTUAL)==0
1109a9cdb904Sdrh        && sqlite3ExprIsTableConstraint(pExpr, pItem)
1110fa35f5c5Sdrh       ){
1111fa35f5c5Sdrh         sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
1112fa35f5c5Sdrh       }
1113fa35f5c5Sdrh     }
1114fa35f5c5Sdrh     if( pLoop->wsFlags & WHERE_IPK ){
1115fa35f5c5Sdrh       int r1 = sqlite3GetTempReg(pParse);
1116fa35f5c5Sdrh       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1);
1117fa35f5c5Sdrh       sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
111835685d3eSdrh       sqlite3ReleaseTempReg(pParse, r1);
1119fa35f5c5Sdrh     }else{
1120fa35f5c5Sdrh       Index *pIdx = pLoop->u.btree.pIndex;
1121770dade2Sdrh       int n = pLoop->u.btree.nEq;
112235685d3eSdrh       int r1 = sqlite3GetTempRange(pParse, n);
1123fa35f5c5Sdrh       int jj;
1124fa35f5c5Sdrh       for(jj=0; jj<n; jj++){
1125fa35f5c5Sdrh         int iCol = pIdx->aiColumn[jj];
112650fb7e09Sdrh         assert( pIdx->pTable==pItem->pTab );
1127fa35f5c5Sdrh         sqlite3ExprCodeGetColumnOfTable(v, pIdx->pTable, iCur, iCol,r1+jj);
1128fa35f5c5Sdrh       }
1129fa35f5c5Sdrh       sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
113035685d3eSdrh       sqlite3ReleaseTempRange(pParse, r1, n);
1131fa35f5c5Sdrh     }
1132fa35f5c5Sdrh     sqlite3VdbeResolveLabel(v, addrCont);
113350fb7e09Sdrh     sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
1134067c60cfSdrh     VdbeCoverage(v);
1135fa35f5c5Sdrh     sqlite3VdbeJumpHere(v, addrTop);
11366ae49e67Sdrh     pLoop->wsFlags &= ~WHERE_BLOOMFILTER;
11376ae49e67Sdrh     if( OptimizationDisabled(pParse->db, SQLITE_BloomPulldown) ) break;
1138c5860af0Sdrh     while( ++iLevel < pWInfo->nLevel ){
1139ff55da36Sdrh       const SrcItem *pTabItem;
11406ae49e67Sdrh       pLevel = &pWInfo->a[iLevel];
1141ff55da36Sdrh       pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
1142a76ac88aSdrh       if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ) ) continue;
11436ae49e67Sdrh       pLoop = pLevel->pWLoop;
11444f2006ddSdrh       if( NEVER(pLoop==0) ) continue;
1145761d64b7Sdrh       if( pLoop->prereq & notReady ) continue;
1146c5860af0Sdrh       if( (pLoop->wsFlags & (WHERE_BLOOMFILTER|WHERE_COLUMN_IN))
1147c5860af0Sdrh                  ==WHERE_BLOOMFILTER
1148c5860af0Sdrh       ){
1149dc56dc93Sdrh         /* This is a candidate for bloom-filter pull-down (early evaluation).
1150c5860af0Sdrh         ** The test that WHERE_COLUMN_IN is omitted is important, as we are
1151c5860af0Sdrh         ** not able to do early evaluation of bloom filters that make use of
1152c5860af0Sdrh         ** the IN operator */
1153dc56dc93Sdrh         break;
1154dc56dc93Sdrh       }
11556ae49e67Sdrh     }
11566ae49e67Sdrh   }while( iLevel < pWInfo->nLevel );
11576ae49e67Sdrh   sqlite3VdbeJumpHere(v, addrOnce);
1158fa35f5c5Sdrh }
1159fa35f5c5Sdrh 
1160fa35f5c5Sdrh 
11611d46146bSdanielk1977 #ifndef SQLITE_OMIT_VIRTUALTABLE
11621d46146bSdanielk1977 /*
11631d46146bSdanielk1977 ** Allocate and populate an sqlite3_index_info structure. It is the
11641d46146bSdanielk1977 ** responsibility of the caller to eventually release the structure
116582801a5bSdrh ** by passing the pointer returned by this function to freeIndexInfo().
11661d46146bSdanielk1977 */
allocateIndexInfo(WhereInfo * pWInfo,WhereClause * pWC,Bitmask mUnusable,SrcItem * pSrc,u16 * pmNoOmit)11675346e95dSdrh static sqlite3_index_info *allocateIndexInfo(
1168ec778d27Sdrh   WhereInfo *pWInfo,              /* The WHERE clause */
1169efc88d02Sdrh   WhereClause *pWC,               /* The WHERE clause being analyzed */
11704f20cd40Sdan   Bitmask mUnusable,              /* Ignore terms with these prereqs */
11717601294aSdrh   SrcItem *pSrc,                  /* The FROM clause term that is the vtab */
11726256c1c2Sdan   u16 *pmNoOmit                   /* Mask of terms not to omit */
11735346e95dSdrh ){
11741d46146bSdanielk1977   int i, j;
11751d46146bSdanielk1977   int nTerm;
1176ec778d27Sdrh   Parse *pParse = pWInfo->pParse;
11779eff6167Sdrh   struct sqlite3_index_constraint *pIdxCons;
11789eff6167Sdrh   struct sqlite3_index_orderby *pIdxOrderBy;
11799eff6167Sdrh   struct sqlite3_index_constraint_usage *pUsage;
1180efc88d02Sdrh   struct HiddenIndexInfo *pHidden;
11819eff6167Sdrh   WhereTerm *pTerm;
11829eff6167Sdrh   int nOrderBy;
11831d46146bSdanielk1977   sqlite3_index_info *pIdxInfo;
11846256c1c2Sdan   u16 mNoOmit = 0;
11858a95d3d4Sdrh   const Table *pTab;
1186ec778d27Sdrh   int eDistinct = 0;
1187ec778d27Sdrh   ExprList *pOrderBy = pWInfo->pOrderBy;
11889eff6167Sdrh 
118952576b78Sdrh   assert( pSrc!=0 );
11908a95d3d4Sdrh   pTab = pSrc->pTab;
11918a95d3d4Sdrh   assert( pTab!=0 );
11928a95d3d4Sdrh   assert( IsVirtual(pTab) );
119352576b78Sdrh 
11948a95d3d4Sdrh   /* Find all WHERE clause constraints referring to this virtual table.
11958a95d3d4Sdrh   ** Mark each term with the TERM_OK flag.  Set nTerm to the number of
11968a95d3d4Sdrh   ** terms found.
11978a95d3d4Sdrh   */
11989eff6167Sdrh   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
11998a95d3d4Sdrh     pTerm->wtFlags &= ~TERM_OK;
12009eff6167Sdrh     if( pTerm->leftCursor != pSrc->iCursor ) continue;
12014f20cd40Sdan     if( pTerm->prereqRight & mUnusable ) continue;
12027a5bcc0fSdrh     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
12037a5bcc0fSdrh     testcase( pTerm->eOperator & WO_IN );
12047a5bcc0fSdrh     testcase( pTerm->eOperator & WO_ISNULL );
1205ee14587cSdrh     testcase( pTerm->eOperator & WO_IS );
1206a4ff8250Sdan     testcase( pTerm->eOperator & WO_ALL );
1207d03024d8Sdan     if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
1208b4256996Sdrh     if( pTerm->wtFlags & TERM_VNULL ) continue;
12090fe7e7d9Sdrh 
1210220f0d6fSdrh     assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
12118a95d3d4Sdrh     assert( pTerm->u.x.leftColumn>=XN_ROWID );
12128a95d3d4Sdrh     assert( pTerm->u.x.leftColumn<pTab->nCol );
1213faaacd3fSdrh     if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
1214faaacd3fSdrh      && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
12158a95d3d4Sdrh     ){
12168a95d3d4Sdrh       continue;
12178a95d3d4Sdrh     }
12189eff6167Sdrh     nTerm++;
12198a95d3d4Sdrh     pTerm->wtFlags |= TERM_OK;
12209eff6167Sdrh   }
12219eff6167Sdrh 
12229eff6167Sdrh   /* If the ORDER BY clause contains only columns in the current
12239eff6167Sdrh   ** virtual table then allocate space for the aOrderBy part of
12249eff6167Sdrh   ** the sqlite3_index_info structure.
12259eff6167Sdrh   */
12269eff6167Sdrh   nOrderBy = 0;
12279eff6167Sdrh   if( pOrderBy ){
122856f1b99dSdrh     int n = pOrderBy->nExpr;
122956f1b99dSdrh     for(i=0; i<n; i++){
12309eff6167Sdrh       Expr *pExpr = pOrderBy->a[i].pExpr;
123152576b78Sdrh       Expr *pE2;
123252576b78Sdrh 
1233e1961c55Sdrh       /* Skip over constant terms in the ORDER BY clause */
1234e1961c55Sdrh       if( sqlite3ExprIsConstant(pExpr) ){
1235e1961c55Sdrh         continue;
1236e1961c55Sdrh       }
1237e1961c55Sdrh 
123852576b78Sdrh       /* Virtual tables are unable to deal with NULLS FIRST */
1239d88fd539Sdrh       if( pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) break;
124052576b78Sdrh 
124152576b78Sdrh       /* First case - a direct column references without a COLLATE operator */
124252576b78Sdrh       if( pExpr->op==TK_COLUMN && pExpr->iTable==pSrc->iCursor ){
12438a95d3d4Sdrh         assert( pExpr->iColumn>=XN_ROWID && pExpr->iColumn<pTab->nCol );
124452576b78Sdrh         continue;
124552576b78Sdrh       }
124652576b78Sdrh 
124752576b78Sdrh       /* 2nd case - a column reference with a COLLATE operator.  Only match
124852576b78Sdrh       ** of the COLLATE operator matches the collation of the column. */
124952576b78Sdrh       if( pExpr->op==TK_COLLATE
125052576b78Sdrh        && (pE2 = pExpr->pLeft)->op==TK_COLUMN
125152576b78Sdrh        && pE2->iTable==pSrc->iCursor
125252576b78Sdrh       ){
125352576b78Sdrh         const char *zColl;  /* The collating sequence name */
125452576b78Sdrh         assert( !ExprHasProperty(pExpr, EP_IntValue) );
125552576b78Sdrh         assert( pExpr->u.zToken!=0 );
12568a95d3d4Sdrh         assert( pE2->iColumn>=XN_ROWID && pE2->iColumn<pTab->nCol );
125752576b78Sdrh         pExpr->iColumn = pE2->iColumn;
125852576b78Sdrh         if( pE2->iColumn<0 ) continue;  /* Collseq does not matter for rowid */
12598a95d3d4Sdrh         zColl = sqlite3ColumnColl(&pTab->aCol[pE2->iColumn]);
126052576b78Sdrh         if( zColl==0 ) zColl = sqlite3StrBINARY;
126152576b78Sdrh         if( sqlite3_stricmp(pExpr->u.zToken, zColl)==0 ) continue;
126252576b78Sdrh       }
126352576b78Sdrh 
126452576b78Sdrh       /* No matches cause a break out of the loop */
126552576b78Sdrh       break;
12669eff6167Sdrh     }
126756f1b99dSdrh     if( i==n ){
126856f1b99dSdrh       nOrderBy = n;
1269ece092e7Sdan       if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) ){
1270ece092e7Sdan         eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
1271ece092e7Sdan       }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
1272ece092e7Sdan         eDistinct = 1;
1273ec778d27Sdrh       }
12749eff6167Sdrh     }
12759eff6167Sdrh   }
12769eff6167Sdrh 
12779eff6167Sdrh   /* Allocate the sqlite3_index_info structure
12789eff6167Sdrh   */
127926783a58Sdanielk1977   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
12809eff6167Sdrh                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
128182801a5bSdrh                            + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden)
128282801a5bSdrh                            + sizeof(sqlite3_value*)*nTerm );
12839eff6167Sdrh   if( pIdxInfo==0 ){
12849eff6167Sdrh     sqlite3ErrorMsg(pParse, "out of memory");
12851d46146bSdanielk1977     return 0;
12869eff6167Sdrh   }
1287efc88d02Sdrh   pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
128882801a5bSdrh   pIdxCons = (struct sqlite3_index_constraint*)&pHidden->aRhs[nTerm];
12899eff6167Sdrh   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
12909eff6167Sdrh   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
1291cfcf4de4Sdrh   pIdxInfo->aConstraint = pIdxCons;
1292cfcf4de4Sdrh   pIdxInfo->aOrderBy = pIdxOrderBy;
1293cfcf4de4Sdrh   pIdxInfo->aConstraintUsage = pUsage;
1294efc88d02Sdrh   pHidden->pWC = pWC;
1295efc88d02Sdrh   pHidden->pParse = pParse;
1296ec778d27Sdrh   pHidden->eDistinct = eDistinct;
1297a9f18f01Sdrh   pHidden->mIn = 0;
12989eff6167Sdrh   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
1299d03024d8Sdan     u16 op;
13008a95d3d4Sdrh     if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
130175fa2663Sdrh     pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
13029eff6167Sdrh     pIdxCons[j].iTermOffset = i;
1303d03024d8Sdan     op = pTerm->eOperator & WO_ALL;
1304a9f18f01Sdrh     if( op==WO_IN ){
130551896e6fSdrh       if( (pTerm->wtFlags & TERM_SLICE)==0 ){
1306a9f18f01Sdrh         pHidden->mIn |= SMASKBIT32(j);
130751896e6fSdrh       }
1308a9f18f01Sdrh       op = WO_EQ;
1309a9f18f01Sdrh     }
1310303a69b5Sdrh     if( op==WO_AUX ){
1311d03024d8Sdan       pIdxCons[j].op = pTerm->eMatchOp;
1312d03024d8Sdan     }else if( op & (WO_ISNULL|WO_IS) ){
1313d03024d8Sdan       if( op==WO_ISNULL ){
1314d03024d8Sdan         pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
1315d03024d8Sdan       }else{
1316d03024d8Sdan         pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
131707bdba86Sdan       }
1318d03024d8Sdan     }else{
1319d03024d8Sdan       pIdxCons[j].op = (u8)op;
13207f375901Sdrh       /* The direct assignment in the previous line is possible only because
13217f375901Sdrh       ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
13227f375901Sdrh       ** following asserts verify this fact. */
13239eff6167Sdrh       assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
13249eff6167Sdrh       assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
13259eff6167Sdrh       assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
13269eff6167Sdrh       assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
13279eff6167Sdrh       assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
1328303a69b5Sdrh       assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
13296256c1c2Sdan 
13306256c1c2Sdan       if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
13316256c1c2Sdan        && sqlite3ExprIsVector(pTerm->pExpr->pRight)
13326256c1c2Sdan       ){
1333b6c94725Sdrh         testcase( j!=i );
1334b6c94725Sdrh         if( j<16 ) mNoOmit |= (1 << j);
13356256c1c2Sdan         if( op==WO_LT ) pIdxCons[j].op = WO_LE;
13366256c1c2Sdan         if( op==WO_GT ) pIdxCons[j].op = WO_GE;
13376256c1c2Sdan       }
1338d03024d8Sdan     }
13396256c1c2Sdan 
13409eff6167Sdrh     j++;
13419eff6167Sdrh   }
13428a95d3d4Sdrh   assert( j==nTerm );
1343cfcf4de4Sdrh   pIdxInfo->nConstraint = j;
1344e1961c55Sdrh   for(i=j=0; i<nOrderBy; i++){
13459eff6167Sdrh     Expr *pExpr = pOrderBy->a[i].pExpr;
1346e1961c55Sdrh     if( sqlite3ExprIsConstant(pExpr) ) continue;
134752576b78Sdrh     assert( pExpr->op==TK_COLUMN
134852576b78Sdrh          || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
134952576b78Sdrh               && pExpr->iColumn==pExpr->pLeft->iColumn) );
1350e1961c55Sdrh     pIdxOrderBy[j].iColumn = pExpr->iColumn;
1351d88fd539Sdrh     pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC;
1352e1961c55Sdrh     j++;
13539eff6167Sdrh   }
1354e1961c55Sdrh   pIdxInfo->nOrderBy = j;
13551d46146bSdanielk1977 
13566256c1c2Sdan   *pmNoOmit = mNoOmit;
13571d46146bSdanielk1977   return pIdxInfo;
13581d46146bSdanielk1977 }
13591d46146bSdanielk1977 
13601d46146bSdanielk1977 /*
136182801a5bSdrh ** Free an sqlite3_index_info structure allocated by allocateIndexInfo()
136282801a5bSdrh ** and possibly modified by xBestIndex methods.
136382801a5bSdrh */
freeIndexInfo(sqlite3 * db,sqlite3_index_info * pIdxInfo)136482801a5bSdrh static void freeIndexInfo(sqlite3 *db, sqlite3_index_info *pIdxInfo){
136582801a5bSdrh   HiddenIndexInfo *pHidden;
136682801a5bSdrh   int i;
136782801a5bSdrh   assert( pIdxInfo!=0 );
136882801a5bSdrh   pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
136982801a5bSdrh   assert( pHidden->pParse!=0 );
137082801a5bSdrh   assert( pHidden->pParse->db==db );
137182801a5bSdrh   for(i=0; i<pIdxInfo->nConstraint; i++){
1372991d1085Sdrh     sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
137382801a5bSdrh     pHidden->aRhs[i] = 0;
137482801a5bSdrh   }
137582801a5bSdrh   sqlite3DbFree(db, pIdxInfo);
137682801a5bSdrh }
137782801a5bSdrh 
137882801a5bSdrh /*
13791d46146bSdanielk1977 ** The table object reference passed as the second argument to this function
13801d46146bSdanielk1977 ** must represent a virtual table. This function invokes the xBestIndex()
13813b48e8c9Sdrh ** method of the virtual table with the sqlite3_index_info object that
13823b48e8c9Sdrh ** comes in as the 3rd argument to this function.
13831d46146bSdanielk1977 **
138432dcc847Sdrh ** If an error occurs, pParse is populated with an error message and an
138532dcc847Sdrh ** appropriate error code is returned.  A return of SQLITE_CONSTRAINT from
138632dcc847Sdrh ** xBestIndex is not considered an error.  SQLITE_CONSTRAINT indicates that
138732dcc847Sdrh ** the current configuration of "unusable" flags in sqlite3_index_info can
138832dcc847Sdrh ** not result in a valid plan.
13891d46146bSdanielk1977 **
13901d46146bSdanielk1977 ** Whether or not an error is returned, it is the responsibility of the
13911d46146bSdanielk1977 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
13921d46146bSdanielk1977 ** that this is required.
13931d46146bSdanielk1977 */
vtabBestIndex(Parse * pParse,Table * pTab,sqlite3_index_info * p)13941d46146bSdanielk1977 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
1395595a523aSdanielk1977   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
13961d46146bSdanielk1977   int rc;
13971d46146bSdanielk1977 
1398cfcf4de4Sdrh   whereTraceIndexInfoInputs(p);
13993832c3c1Sdrh   pParse->db->nSchemaLock++;
14001d46146bSdanielk1977   rc = pVtab->pModule->xBestIndex(pVtab, p);
14013832c3c1Sdrh   pParse->db->nSchemaLock--;
1402cfcf4de4Sdrh   whereTraceIndexInfoOutputs(p);
14031d46146bSdanielk1977 
140432dcc847Sdrh   if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
14051d46146bSdanielk1977     if( rc==SQLITE_NOMEM ){
14064a642b60Sdrh       sqlite3OomFault(pParse->db);
14071d46146bSdanielk1977     }else if( !pVtab->zErrMsg ){
14081d46146bSdanielk1977       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
14091d46146bSdanielk1977     }else{
14101d46146bSdanielk1977       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
14111d46146bSdanielk1977     }
14121d46146bSdanielk1977   }
1413b975598eSdrh   sqlite3_free(pVtab->zErrMsg);
14141d46146bSdanielk1977   pVtab->zErrMsg = 0;
141532dcc847Sdrh   return rc;
14161d46146bSdanielk1977 }
14177ba39a92Sdrh #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
14181d46146bSdanielk1977 
1419175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
142028c4cf42Sdrh /*
1421faacf17cSdrh ** Estimate the location of a particular key among all keys in an
1422faacf17cSdrh ** index.  Store the results in aStat as follows:
1423e847d324Sdrh **
1424a3d0c136Sdan **    aStat[0]      Est. number of rows less than pRec
1425a3d0c136Sdan **    aStat[1]      Est. number of rows equal to pRec
142602fa4696Sdan **
14276d3f91d0Sdrh ** Return the index of the sample that is the smallest sample that
1428a3d0c136Sdan ** is greater than or equal to pRec. Note that this index is not an index
1429a3d0c136Sdan ** into the aSample[] array - it is an index into a virtual set of samples
1430a3d0c136Sdan ** based on the contents of aSample[] and the number of fields in record
1431a3d0c136Sdan ** pRec.
143202fa4696Sdan */
whereKeyStats(Parse * pParse,Index * pIdx,UnpackedRecord * pRec,int roundUp,tRowcnt * aStat)14336d3f91d0Sdrh static int whereKeyStats(
143402fa4696Sdan   Parse *pParse,              /* Database connection */
143502fa4696Sdan   Index *pIdx,                /* Index to consider domain of */
14367a419235Sdan   UnpackedRecord *pRec,       /* Vector of values to consider */
1437faacf17cSdrh   int roundUp,                /* Round up if true.  Round down if false */
1438faacf17cSdrh   tRowcnt *aStat              /* OUT: stats written here */
143902fa4696Sdan ){
1440f52bb8d3Sdan   IndexSample *aSample = pIdx->aSample;
1441fbc38de9Sdrh   int iCol;                   /* Index of required stats in anEq[] etc. */
1442a3d0c136Sdan   int i;                      /* Index of first sample >= pRec */
1443a3d0c136Sdan   int iSample;                /* Smallest sample larger than or equal to pRec */
144484c309b6Sdan   int iMin = 0;               /* Smallest sample not yet tested */
144584c309b6Sdan   int iTest;                  /* Next sample to test */
144684c309b6Sdan   int res;                    /* Result of comparison operation */
1447a3d0c136Sdan   int nField;                 /* Number of fields in pRec */
1448a3d0c136Sdan   tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
144902fa4696Sdan 
14504f991890Sdrh #ifndef SQLITE_DEBUG
14514f991890Sdrh   UNUSED_PARAMETER( pParse );
14524f991890Sdrh #endif
14537f59475fSdrh   assert( pRec!=0 );
14545c62486cSdrh   assert( pIdx->nSample>0 );
1455b3623e0aSdrh   assert( pRec->nField>0 );
1456a3d0c136Sdan 
1457a3d0c136Sdan   /* Do a binary search to find the first sample greater than or equal
1458a3d0c136Sdan   ** to pRec. If pRec contains a single field, the set of samples to search
1459a3d0c136Sdan   ** is simply the aSample[] array. If the samples in aSample[] contain more
1460a3d0c136Sdan   ** than one fields, all fields following the first are ignored.
1461a3d0c136Sdan   **
1462a3d0c136Sdan   ** If pRec contains N fields, where N is more than one, then as well as the
1463a3d0c136Sdan   ** samples in aSample[] (truncated to N fields), the search also has to
1464a3d0c136Sdan   ** consider prefixes of those samples. For example, if the set of samples
1465a3d0c136Sdan   ** in aSample is:
1466a3d0c136Sdan   **
1467a3d0c136Sdan   **     aSample[0] = (a, 5)
1468a3d0c136Sdan   **     aSample[1] = (a, 10)
1469a3d0c136Sdan   **     aSample[2] = (b, 5)
1470a3d0c136Sdan   **     aSample[3] = (c, 100)
1471a3d0c136Sdan   **     aSample[4] = (c, 105)
1472a3d0c136Sdan   **
1473a3d0c136Sdan   ** Then the search space should ideally be the samples above and the
1474a3d0c136Sdan   ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
1475a3d0c136Sdan   ** the code actually searches this set:
1476a3d0c136Sdan   **
1477a3d0c136Sdan   **     0: (a)
1478a3d0c136Sdan   **     1: (a, 5)
1479a3d0c136Sdan   **     2: (a, 10)
1480a3d0c136Sdan   **     3: (a, 10)
1481a3d0c136Sdan   **     4: (b)
1482a3d0c136Sdan   **     5: (b, 5)
1483a3d0c136Sdan   **     6: (c)
1484a3d0c136Sdan   **     7: (c, 100)
1485a3d0c136Sdan   **     8: (c, 105)
1486a3d0c136Sdan   **     9: (c, 105)
1487a3d0c136Sdan   **
1488a3d0c136Sdan   ** For each sample in the aSample[] array, N samples are present in the
1489a3d0c136Sdan   ** effective sample array. In the above, samples 0 and 1 are based on
1490a3d0c136Sdan   ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
1491a3d0c136Sdan   **
1492a3d0c136Sdan   ** Often, sample i of each block of N effective samples has (i+1) fields.
1493a3d0c136Sdan   ** Except, each sample may be extended to ensure that it is greater than or
1494a3d0c136Sdan   ** equal to the previous sample in the array. For example, in the above,
1495a3d0c136Sdan   ** sample 2 is the first sample of a block of N samples, so at first it
1496a3d0c136Sdan   ** appears that it should be 1 field in size. However, that would make it
1497a3d0c136Sdan   ** smaller than sample 1, so the binary search would not work. As a result,
1498a3d0c136Sdan   ** it is extended to two fields. The duplicates that this creates do not
1499a3d0c136Sdan   ** cause any problems.
1500a3d0c136Sdan   */
1501b3623e0aSdrh   nField = MIN(pRec->nField, pIdx->nSample);
1502a3d0c136Sdan   iCol = 0;
1503a3d0c136Sdan   iSample = pIdx->nSample * nField;
150484c309b6Sdan   do{
1505a3d0c136Sdan     int iSamp;                    /* Index in aSample[] of test sample */
1506a3d0c136Sdan     int n;                        /* Number of fields in test sample */
1507a3d0c136Sdan 
1508a3d0c136Sdan     iTest = (iMin+iSample)/2;
1509a3d0c136Sdan     iSamp = iTest / nField;
1510a3d0c136Sdan     if( iSamp>0 ){
1511a3d0c136Sdan       /* The proposed effective sample is a prefix of sample aSample[iSamp].
1512a3d0c136Sdan       ** Specifically, the shortest prefix of at least (1 + iTest%nField)
1513a3d0c136Sdan       ** fields that is greater than the previous effective sample.  */
1514a3d0c136Sdan       for(n=(iTest % nField) + 1; n<nField; n++){
1515a3d0c136Sdan         if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
1516faacf17cSdrh       }
1517a3d0c136Sdan     }else{
1518a3d0c136Sdan       n = iTest + 1;
1519a3d0c136Sdan     }
1520a3d0c136Sdan 
1521a3d0c136Sdan     pRec->nField = n;
1522a3d0c136Sdan     res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
1523a3d0c136Sdan     if( res<0 ){
1524a3d0c136Sdan       iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
1525a3d0c136Sdan       iMin = iTest+1;
1526a3d0c136Sdan     }else if( res==0 && n<nField ){
1527a3d0c136Sdan       iLower = aSample[iSamp].anLt[n-1];
1528a3d0c136Sdan       iMin = iTest+1;
1529a3d0c136Sdan       res = -1;
1530a3d0c136Sdan     }else{
1531a3d0c136Sdan       iSample = iTest;
1532a3d0c136Sdan       iCol = n-1;
1533a3d0c136Sdan     }
1534a3d0c136Sdan   }while( res && iMin<iSample );
1535a3d0c136Sdan   i = iSample / nField;
153602fa4696Sdan 
153784c309b6Sdan #ifdef SQLITE_DEBUG
153884c309b6Sdan   /* The following assert statements check that the binary search code
153984c309b6Sdan   ** above found the right answer. This block serves no purpose other
154084c309b6Sdan   ** than to invoke the asserts.  */
1541a3d0c136Sdan   if( pParse->db->mallocFailed==0 ){
154284c309b6Sdan     if( res==0 ){
1543a3d0c136Sdan       /* If (res==0) is true, then pRec must be equal to sample i. */
154484c309b6Sdan       assert( i<pIdx->nSample );
1545a3d0c136Sdan       assert( iCol==nField-1 );
1546a3d0c136Sdan       pRec->nField = nField;
154775179dedSdrh       assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
1548a3d0c136Sdan            || pParse->db->mallocFailed
1549a3d0c136Sdan       );
155002fa4696Sdan     }else{
1551a3d0c136Sdan       /* Unless i==pIdx->nSample, indicating that pRec is larger than
1552a3d0c136Sdan       ** all samples in the aSample[] array, pRec must be smaller than the
1553a3d0c136Sdan       ** (iCol+1) field prefix of sample i.  */
1554a3d0c136Sdan       assert( i<=pIdx->nSample && i>=0 );
1555a3d0c136Sdan       pRec->nField = iCol+1;
155684c309b6Sdan       assert( i==pIdx->nSample
155775179dedSdrh            || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
15580e1f0029Sdrh            || pParse->db->mallocFailed );
1559a3d0c136Sdan 
1560a3d0c136Sdan       /* if i==0 and iCol==0, then record pRec is smaller than all samples
1561a3d0c136Sdan       ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
1562a3d0c136Sdan       ** be greater than or equal to the (iCol) field prefix of sample i.
1563a3d0c136Sdan       ** If (i>0), then pRec must also be greater than sample (i-1).  */
1564a3d0c136Sdan       if( iCol>0 ){
1565a3d0c136Sdan         pRec->nField = iCol;
1566a3d0c136Sdan         assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
15670e1f0029Sdrh              || pParse->db->mallocFailed );
156802fa4696Sdan       }
1569a3d0c136Sdan       if( i>0 ){
1570a3d0c136Sdan         pRec->nField = nField;
1571a3d0c136Sdan         assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
1572a3d0c136Sdan              || pParse->db->mallocFailed );
1573a3d0c136Sdan       }
1574a3d0c136Sdan     }
1575a3d0c136Sdan   }
157684c309b6Sdan #endif /* ifdef SQLITE_DEBUG */
157702fa4696Sdan 
157884c309b6Sdan   if( res==0 ){
1579a3d0c136Sdan     /* Record pRec is equal to sample i */
1580a3d0c136Sdan     assert( iCol==nField-1 );
1581eea568d6Sdan     aStat[0] = aSample[i].anLt[iCol];
1582eea568d6Sdan     aStat[1] = aSample[i].anEq[iCol];
1583faacf17cSdrh   }else{
1584a3d0c136Sdan     /* At this point, the (iCol+1) field prefix of aSample[i] is the first
1585a3d0c136Sdan     ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
1586a3d0c136Sdan     ** is larger than all samples in the array. */
1587a3d0c136Sdan     tRowcnt iUpper, iGap;
1588a3d0c136Sdan     if( i>=pIdx->nSample ){
15898c3cc71aSdan       iUpper = pIdx->nRowEst0;
1590faacf17cSdrh     }else{
1591a3d0c136Sdan       iUpper = aSample[i].anLt[iCol];
1592faacf17cSdrh     }
1593a3d0c136Sdan 
1594faacf17cSdrh     if( iLower>=iUpper ){
1595faacf17cSdrh       iGap = 0;
1596faacf17cSdrh     }else{
1597faacf17cSdrh       iGap = iUpper - iLower;
1598faacf17cSdrh     }
1599faacf17cSdrh     if( roundUp ){
1600faacf17cSdrh       iGap = (iGap*2)/3;
1601faacf17cSdrh     }else{
1602faacf17cSdrh       iGap = iGap/3;
1603faacf17cSdrh     }
1604faacf17cSdrh     aStat[0] = iLower + iGap;
160563ad86e7Sdrh     aStat[1] = pIdx->aAvgEq[nField-1];
160602fa4696Sdan   }
1607a3d0c136Sdan 
1608a3d0c136Sdan   /* Restore the pRec->nField value before returning.  */
1609a3d0c136Sdan   pRec->nField = nField;
16106d3f91d0Sdrh   return i;
161102fa4696Sdan }
1612175b8f06Sdrh #endif /* SQLITE_ENABLE_STAT4 */
1613937d0deaSdan 
1614937d0deaSdan /*
1615aa9933c1Sdan ** If it is not NULL, pTerm is a term that provides an upper or lower
1616aa9933c1Sdan ** bound on a range scan. Without considering pTerm, it is estimated
1617aa9933c1Sdan ** that the scan will visit nNew rows. This function returns the number
1618aa9933c1Sdan ** estimated to be visited after taking pTerm into account.
1619aa9933c1Sdan **
1620aa9933c1Sdan ** If the user explicitly specified a likelihood() value for this term,
1621aa9933c1Sdan ** then the return value is the likelihood multiplied by the number of
1622aa9933c1Sdan ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
1623aa9933c1Sdan ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
1624aa9933c1Sdan */
whereRangeAdjust(WhereTerm * pTerm,LogEst nNew)1625aa9933c1Sdan static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
1626aa9933c1Sdan   LogEst nRet = nNew;
1627aa9933c1Sdan   if( pTerm ){
1628aa9933c1Sdan     if( pTerm->truthProb<=0 ){
1629aa9933c1Sdan       nRet += pTerm->truthProb;
16307de2a1faSdan     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
1631aa9933c1Sdan       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
1632aa9933c1Sdan     }
1633aa9933c1Sdan   }
1634aa9933c1Sdan   return nRet;
1635aa9933c1Sdan }
1636aa9933c1Sdan 
1637567cc1e4Sdrh 
1638175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
1639567cc1e4Sdrh /*
1640567cc1e4Sdrh ** Return the affinity for a single column of an index.
1641567cc1e4Sdrh */
sqlite3IndexColumnAffinity(sqlite3 * db,Index * pIdx,int iCol)1642d66e5794Sdan char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
16438ffddeb7Sdrh   assert( iCol>=0 && iCol<pIdx->nColumn );
1644567cc1e4Sdrh   if( !pIdx->zColAff ){
1645567cc1e4Sdrh     if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
1646567cc1e4Sdrh   }
164796fb16eeSdrh   assert( pIdx->zColAff[iCol]!=0 );
1648567cc1e4Sdrh   return pIdx->zColAff[iCol];
1649567cc1e4Sdrh }
1650567cc1e4Sdrh #endif
1651567cc1e4Sdrh 
1652567cc1e4Sdrh 
1653175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
1654aa9933c1Sdan /*
1655b0b8290eSdan ** This function is called to estimate the number of rows visited by a
1656b0b8290eSdan ** range-scan on a skip-scan index. For example:
1657b0b8290eSdan **
1658b0b8290eSdan **   CREATE INDEX i1 ON t1(a, b, c);
1659b0b8290eSdan **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
1660b0b8290eSdan **
1661b0b8290eSdan ** Value pLoop->nOut is currently set to the estimated number of rows
1662b0b8290eSdan ** visited for scanning (a=? AND b=?). This function reduces that estimate
1663b0b8290eSdan ** by some factor to account for the (c BETWEEN ? AND ?) expression based
1664b0b8290eSdan ** on the stat4 data for the index. this scan will be peformed multiple
1665b0b8290eSdan ** times (once for each (a,b) combination that matches a=?) is dealt with
1666b0b8290eSdan ** by the caller.
1667b0b8290eSdan **
1668b0b8290eSdan ** It does this by scanning through all stat4 samples, comparing values
1669b0b8290eSdan ** extracted from pLower and pUpper with the corresponding column in each
1670b0b8290eSdan ** sample. If L and U are the number of samples found to be less than or
1671b0b8290eSdan ** equal to the values extracted from pLower and pUpper respectively, and
1672b0b8290eSdan ** N is the total number of samples, the pLoop->nOut value is adjusted
1673b0b8290eSdan ** as follows:
1674b0b8290eSdan **
1675b0b8290eSdan **   nOut = nOut * ( min(U - L, 1) / N )
1676b0b8290eSdan **
1677b0b8290eSdan ** If pLower is NULL, or a value cannot be extracted from the term, L is
1678b0b8290eSdan ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
1679b0b8290eSdan ** U is set to N.
1680b0b8290eSdan **
1681b0b8290eSdan ** Normally, this function sets *pbDone to 1 before returning. However,
1682b0b8290eSdan ** if no value can be extracted from either pLower or pUpper (and so the
1683b0b8290eSdan ** estimate of the number of rows delivered remains unchanged), *pbDone
1684b0b8290eSdan ** is left as is.
1685b0b8290eSdan **
1686b0b8290eSdan ** If an error occurs, an SQLite error code is returned. Otherwise,
1687b0b8290eSdan ** SQLITE_OK.
1688b0b8290eSdan */
whereRangeSkipScanEst(Parse * pParse,WhereTerm * pLower,WhereTerm * pUpper,WhereLoop * pLoop,int * pbDone)1689b0b8290eSdan static int whereRangeSkipScanEst(
1690b0b8290eSdan   Parse *pParse,       /* Parsing & code generating context */
1691b0b8290eSdan   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
1692b0b8290eSdan   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
1693b0b8290eSdan   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
1694b0b8290eSdan   int *pbDone          /* Set to true if at least one expr. value extracted */
1695b0b8290eSdan ){
1696b0b8290eSdan   Index *p = pLoop->u.btree.pIndex;
1697b0b8290eSdan   int nEq = pLoop->u.btree.nEq;
1698b0b8290eSdan   sqlite3 *db = pParse->db;
16994e42ba4aSdan   int nLower = -1;
17004e42ba4aSdan   int nUpper = p->nSample+1;
1701b0b8290eSdan   int rc = SQLITE_OK;
17028ffddeb7Sdrh   u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
1703b0b8290eSdan   CollSeq *pColl;
1704b0b8290eSdan 
1705b0b8290eSdan   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
1706b0b8290eSdan   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
1707b0b8290eSdan   sqlite3_value *pVal = 0;        /* Value extracted from record */
1708b0b8290eSdan 
1709b0b8290eSdan   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
1710b0b8290eSdan   if( pLower ){
1711b0b8290eSdan     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
17124e42ba4aSdan     nLower = 0;
1713b0b8290eSdan   }
1714b0b8290eSdan   if( pUpper && rc==SQLITE_OK ){
1715b0b8290eSdan     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
17164e42ba4aSdan     nUpper = p2 ? 0 : p->nSample;
1717b0b8290eSdan   }
1718b0b8290eSdan 
1719b0b8290eSdan   if( p1 || p2 ){
1720b0b8290eSdan     int i;
1721b0b8290eSdan     int nDiff;
1722b0b8290eSdan     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
1723b0b8290eSdan       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
1724b0b8290eSdan       if( rc==SQLITE_OK && p1 ){
1725b0b8290eSdan         int res = sqlite3MemCompare(p1, pVal, pColl);
17264e42ba4aSdan         if( res>=0 ) nLower++;
1727b0b8290eSdan       }
1728b0b8290eSdan       if( rc==SQLITE_OK && p2 ){
1729b0b8290eSdan         int res = sqlite3MemCompare(p2, pVal, pColl);
17304e42ba4aSdan         if( res>=0 ) nUpper++;
1731b0b8290eSdan       }
1732b0b8290eSdan     }
1733b0b8290eSdan     nDiff = (nUpper - nLower);
1734b0b8290eSdan     if( nDiff<=0 ) nDiff = 1;
17354e42ba4aSdan 
17364e42ba4aSdan     /* If there is both an upper and lower bound specified, and the
17374e42ba4aSdan     ** comparisons indicate that they are close together, use the fallback
17384e42ba4aSdan     ** method (assume that the scan visits 1/64 of the rows) for estimating
17394e42ba4aSdan     ** the number of rows visited. Otherwise, estimate the number of rows
17404e42ba4aSdan     ** using the method described in the header comment for this function. */
17414e42ba4aSdan     if( nDiff!=1 || pUpper==0 || pLower==0 ){
17424e42ba4aSdan       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
17434e42ba4aSdan       pLoop->nOut -= nAdjust;
1744b0b8290eSdan       *pbDone = 1;
17454e42ba4aSdan       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
1746fa887454Sdan                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
17474e42ba4aSdan     }
17484e42ba4aSdan 
1749b0b8290eSdan   }else{
1750b0b8290eSdan     assert( *pbDone==0 );
1751b0b8290eSdan   }
1752b0b8290eSdan 
1753b0b8290eSdan   sqlite3ValueFree(p1);
1754b0b8290eSdan   sqlite3ValueFree(p2);
1755b0b8290eSdan   sqlite3ValueFree(pVal);
1756b0b8290eSdan 
1757b0b8290eSdan   return rc;
1758b0b8290eSdan }
1759175b8f06Sdrh #endif /* SQLITE_ENABLE_STAT4 */
1760b0b8290eSdan 
176102fa4696Sdan /*
176202fa4696Sdan ** This function is used to estimate the number of rows that will be visited
176302fa4696Sdan ** by scanning an index for a range of values. The range may have an upper
176402fa4696Sdan ** bound, a lower bound, or both. The WHERE clause terms that set the upper
176502fa4696Sdan ** and lower bounds are represented by pLower and pUpper respectively. For
176602fa4696Sdan ** example, assuming that index p is on t1(a):
176702fa4696Sdan **
176802fa4696Sdan **   ... FROM t1 WHERE a > ? AND a < ? ...
176902fa4696Sdan **                    |_____|   |_____|
177002fa4696Sdan **                       |         |
177102fa4696Sdan **                     pLower    pUpper
177202fa4696Sdan **
177398cdf626Sdrh ** If either of the upper or lower bound is not present, then NULL is passed in
1774cdaca55eSdrh ** place of the corresponding WhereTerm.
177502fa4696Sdan **
17766d3f91d0Sdrh ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
17776cb8d76cSdan ** column subject to the range constraint. Or, equivalently, the number of
17786cb8d76cSdan ** equality constraints optimized by the proposed index scan. For example,
17796cb8d76cSdan ** assuming index p is on t1(a, b), and the SQL query is:
178002fa4696Sdan **
178102fa4696Sdan **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
178202fa4696Sdan **
17836cb8d76cSdan ** then nEq is set to 1 (as the range restricted column, b, is the second
17846cb8d76cSdan ** left-most column of the index). Or, if the query is:
178502fa4696Sdan **
178602fa4696Sdan **   ... FROM t1 WHERE a > ? AND a < ? ...
178702fa4696Sdan **
17886cb8d76cSdan ** then nEq is set to 0.
178902fa4696Sdan **
1790bf539c4dSdrh ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
17916cb8d76cSdan ** number of rows that the index scan is expected to visit without
17926d3f91d0Sdrh ** considering the range constraints. If nEq is 0, then *pnOut is the number of
17936cb8d76cSdan ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
179460ec914cSpeter.d.reid ** to account for the range constraints pLower and pUpper.
179598cdf626Sdrh **
17966cb8d76cSdan ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
179794aa7e09Sdrh ** used, a single range inequality reduces the search space by a factor of 4.
179894aa7e09Sdrh ** and a pair of constraints (x>? AND x<?) reduces the expected number of
179994aa7e09Sdrh ** rows visited by a factor of 64.
180002fa4696Sdan */
whereRangeScanEst(Parse * pParse,WhereLoopBuilder * pBuilder,WhereTerm * pLower,WhereTerm * pUpper,WhereLoop * pLoop)180102fa4696Sdan static int whereRangeScanEst(
1802cdaca55eSdrh   Parse *pParse,       /* Parsing & code generating context */
18037a419235Sdan   WhereLoopBuilder *pBuilder,
1804cdaca55eSdrh   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
1805cdaca55eSdrh   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
1806186ad8ccSdrh   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
180702fa4696Sdan ){
180869188d9aSdan   int rc = SQLITE_OK;
1809186ad8ccSdrh   int nOut = pLoop->nOut;
1810bf539c4dSdrh   LogEst nNew;
181169188d9aSdan 
1812175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
1813186ad8ccSdrh   Index *p = pLoop->u.btree.pIndex;
18144f991890Sdrh   int nEq = pLoop->u.btree.nEq;
181502fa4696Sdan 
18165eae1d1bSdrh   if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)
18175eae1d1bSdrh    && OptimizationEnabled(pParse->db, SQLITE_Stat4)
181872d03a64Sdrh   ){
1819b0b8290eSdan     if( nEq==pBuilder->nRecValid ){
18207a419235Sdan       UnpackedRecord *pRec = pBuilder->pRec;
1821faacf17cSdrh       tRowcnt a[2];
1822d66e5794Sdan       int nBtm = pLoop->u.btree.nBtm;
1823d66e5794Sdan       int nTop = pLoop->u.btree.nTop;
182498cdf626Sdrh 
1825b3c02e21Sdan       /* Variable iLower will be set to the estimate of the number of rows in
1826b3c02e21Sdan       ** the index that are less than the lower bound of the range query. The
1827b3c02e21Sdan       ** lower bound being the concatenation of $P and $L, where $P is the
1828b3c02e21Sdan       ** key-prefix formed by the nEq values matched against the nEq left-most
1829b3c02e21Sdan       ** columns of the index, and $L is the value in pLower.
1830b3c02e21Sdan       **
1831b3c02e21Sdan       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
1832b3c02e21Sdan       ** is not a simple variable or literal value), the lower bound of the
1833b3c02e21Sdan       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
1834b3c02e21Sdan       ** if $L is available, whereKeyStats() is called for both ($P) and
18356d3f91d0Sdrh       ** ($P:$L) and the larger of the two returned values is used.
1836b3c02e21Sdan       **
1837b3c02e21Sdan       ** Similarly, iUpper is to be set to the estimate of the number of rows
1838b3c02e21Sdan       ** less than the upper bound of the range query. Where the upper bound
1839b3c02e21Sdan       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
1840b3c02e21Sdan       ** of iUpper are requested of whereKeyStats() and the smaller used.
18416d3f91d0Sdrh       **
18426d3f91d0Sdrh       ** The number of rows between the two bounds is then just iUpper-iLower.
1843b3c02e21Sdan       */
18446d3f91d0Sdrh       tRowcnt iLower;     /* Rows less than the lower bound */
18456d3f91d0Sdrh       tRowcnt iUpper;     /* Rows less than the upper bound */
18466d3f91d0Sdrh       int iLwrIdx = -2;   /* aSample[] for the lower bound */
18476d3f91d0Sdrh       int iUprIdx = -1;   /* aSample[] for the upper bound */
1848b3c02e21Sdan 
1849b34fc5beSdrh       if( pRec ){
1850b34fc5beSdrh         testcase( pRec->nField!=pBuilder->nRecValid );
1851b34fc5beSdrh         pRec->nField = pBuilder->nRecValid;
1852b34fc5beSdrh       }
1853b3c02e21Sdan       /* Determine iLower and iUpper using ($P) only. */
1854b3c02e21Sdan       if( nEq==0 ){
1855b3c02e21Sdan         iLower = 0;
18569f07cf7bSdrh         iUpper = p->nRowEst0;
1857b3c02e21Sdan       }else{
1858b3c02e21Sdan         /* Note: this call could be optimized away - since the same values must
1859b3c02e21Sdan         ** have been requested when testing key $P in whereEqualScanEst().  */
1860b3c02e21Sdan         whereKeyStats(pParse, p, pRec, 0, a);
1861faacf17cSdrh         iLower = a[0];
1862b3c02e21Sdan         iUpper = a[0] + a[1];
1863faacf17cSdrh       }
1864b3c02e21Sdan 
186569afd998Sdrh       assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
186669afd998Sdrh       assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
1867681fca00Sdrh       assert( p->aSortOrder!=0 );
1868681fca00Sdrh       if( p->aSortOrder[nEq] ){
186969afd998Sdrh         /* The roles of pLower and pUpper are swapped for a DESC index */
187069afd998Sdrh         SWAP(WhereTerm*, pLower, pUpper);
1871d66e5794Sdan         SWAP(int, nBtm, nTop);
187269afd998Sdrh       }
187369afd998Sdrh 
1874b3c02e21Sdan       /* If possible, improve on the iLower estimate using ($P:$L). */
187502fa4696Sdan       if( pLower ){
1876d66e5794Sdan         int n;                    /* Values extracted from pExpr */
187702fa4696Sdan         Expr *pExpr = pLower->pExpr->pRight;
1878d66e5794Sdan         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
1879d66e5794Sdan         if( rc==SQLITE_OK && n ){
1880b3c02e21Sdan           tRowcnt iNew;
1881d66e5794Sdan           u16 mask = WO_GT|WO_LE;
1882d66e5794Sdan           if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
18836d3f91d0Sdrh           iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
1884d66e5794Sdan           iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
1885b3c02e21Sdan           if( iNew>iLower ) iLower = iNew;
1886abfa6d52Sdrh           nOut--;
1887f741e049Sdan           pLower = 0;
188802fa4696Sdan         }
188902fa4696Sdan       }
1890b3c02e21Sdan 
1891b3c02e21Sdan       /* If possible, improve on the iUpper estimate using ($P:$U). */
1892b3c02e21Sdan       if( pUpper ){
1893d66e5794Sdan         int n;                    /* Values extracted from pExpr */
189402fa4696Sdan         Expr *pExpr = pUpper->pExpr->pRight;
1895d66e5794Sdan         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
1896d66e5794Sdan         if( rc==SQLITE_OK && n ){
1897b3c02e21Sdan           tRowcnt iNew;
1898d66e5794Sdan           u16 mask = WO_GT|WO_LE;
1899d66e5794Sdan           if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
19006d3f91d0Sdrh           iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
1901d66e5794Sdan           iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
1902b3c02e21Sdan           if( iNew<iUpper ) iUpper = iNew;
1903abfa6d52Sdrh           nOut--;
1904f741e049Sdan           pUpper = 0;
190502fa4696Sdan         }
1906faacf17cSdrh       }
1907b3c02e21Sdan 
190887cd9321Sdan       pBuilder->pRec = pRec;
190902fa4696Sdan       if( rc==SQLITE_OK ){
1910b8a8e8a5Sdrh         if( iUpper>iLower ){
1911bf539c4dSdrh           nNew = sqlite3LogEst(iUpper - iLower);
19126d3f91d0Sdrh           /* TUNING:  If both iUpper and iLower are derived from the same
19136d3f91d0Sdrh           ** sample, then assume they are 4x more selective.  This brings
19146d3f91d0Sdrh           ** the estimated selectivity more in line with what it would be
1915175b8f06Sdrh           ** if estimated without the use of STAT4 tables. */
19166d3f91d0Sdrh           if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
19177a419235Sdan         }else{
1918bf539c4dSdrh           nNew = 10;        assert( 10==sqlite3LogEst(2) );
191998cdf626Sdrh         }
19206cb8d76cSdan         if( nNew<nOut ){
19216cb8d76cSdan           nOut = nNew;
19226cb8d76cSdan         }
1923ae914d78Sdrh         WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
19246cb8d76cSdan                            (u32)iLower, (u32)iUpper, nOut));
192502fa4696Sdan       }
1926b0b8290eSdan     }else{
1927b0b8290eSdan       int bDone = 0;
1928b0b8290eSdan       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
1929b0b8290eSdan       if( bDone ) return rc;
1930b0b8290eSdan     }
1931faacf17cSdrh   }
19323f022189Sdrh #else
19333f022189Sdrh   UNUSED_PARAMETER(pParse);
19347a419235Sdan   UNUSED_PARAMETER(pBuilder);
193502fa4696Sdan   assert( pLower || pUpper );
1936f741e049Sdan #endif
19377de2a1faSdan   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
1938aa9933c1Sdan   nNew = whereRangeAdjust(pLower, nOut);
1939aa9933c1Sdan   nNew = whereRangeAdjust(pUpper, nNew);
19407de2a1faSdan 
19414dd96a83Sdrh   /* TUNING: If there is both an upper and lower limit and neither limit
19424dd96a83Sdrh   ** has an application-defined likelihood(), assume the range is
194342685f21Sdan   ** reduced by an additional 75%. This means that, by default, an open-ended
194442685f21Sdan   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
194542685f21Sdan   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
194642685f21Sdan   ** match 1/64 of the index. */
19474dd96a83Sdrh   if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
19484dd96a83Sdrh     nNew -= 20;
19494dd96a83Sdrh   }
19507de2a1faSdan 
1951aa9933c1Sdan   nOut -= (pLower!=0) + (pUpper!=0);
1952abfa6d52Sdrh   if( nNew<10 ) nNew = 10;
1953abfa6d52Sdrh   if( nNew<nOut ) nOut = nNew;
1954ae914d78Sdrh #if defined(WHERETRACE_ENABLED)
1955ae914d78Sdrh   if( pLoop->nOut>nOut ){
1956ae914d78Sdrh     WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
1957ae914d78Sdrh                     pLoop->nOut, nOut));
1958ae914d78Sdrh   }
1959ae914d78Sdrh #endif
1960186ad8ccSdrh   pLoop->nOut = (LogEst)nOut;
196102fa4696Sdan   return rc;
196202fa4696Sdan }
196302fa4696Sdan 
1964175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
196582759754Sdrh /*
196682759754Sdrh ** Estimate the number of rows that will be returned based on
196782759754Sdrh ** an equality constraint x=VALUE and where that VALUE occurs in
196882759754Sdrh ** the histogram data.  This only works when x is the left-most
1969175b8f06Sdrh ** column of an index and sqlite_stat4 histogram data is available
1970ac8eb113Sdrh ** for that index.  When pExpr==NULL that means the constraint is
1971ac8eb113Sdrh ** "x IS NULL" instead of "x=VALUE".
197282759754Sdrh **
19730c50fa0fSdrh ** Write the estimated row count into *pnRow and return SQLITE_OK.
19740c50fa0fSdrh ** If unable to make an estimate, leave *pnRow unchanged and return
19750c50fa0fSdrh ** non-zero.
19769b3eb0adSdrh **
19779b3eb0adSdrh ** This routine can fail if it is unable to load a collating sequence
19789b3eb0adSdrh ** required for string comparison, or if unable to allocate memory
19799b3eb0adSdrh ** for a UTF conversion required for comparison.  The error is stored
19809b3eb0adSdrh ** in the pParse structure.
198182759754Sdrh */
whereEqualScanEst(Parse * pParse,WhereLoopBuilder * pBuilder,Expr * pExpr,tRowcnt * pnRow)1982041e09f1Sdrh static int whereEqualScanEst(
198382759754Sdrh   Parse *pParse,       /* Parsing & code generating context */
19847a419235Sdan   WhereLoopBuilder *pBuilder,
19850c50fa0fSdrh   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
1986b8a8e8a5Sdrh   tRowcnt *pnRow       /* Write the revised row estimate here */
198782759754Sdrh ){
19887a419235Sdan   Index *p = pBuilder->pNew->u.btree.pIndex;
19897a419235Sdan   int nEq = pBuilder->pNew->u.btree.nEq;
19907a419235Sdan   UnpackedRecord *pRec = pBuilder->pRec;
199182759754Sdrh   int rc;                   /* Subfunction return code */
1992faacf17cSdrh   tRowcnt a[2];             /* Statistics */
19937a419235Sdan   int bOk;
199482759754Sdrh 
19957a419235Sdan   assert( nEq>=1 );
1996fd984b81Sdan   assert( nEq<=p->nColumn );
199782759754Sdrh   assert( p->aSample!=0 );
19985c62486cSdrh   assert( p->nSample>0 );
19997a419235Sdan   assert( pBuilder->nRecValid<nEq );
20007a419235Sdan 
20017a419235Sdan   /* If values are not available for all fields of the index to the left
20027a419235Sdan   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
20037a419235Sdan   if( pBuilder->nRecValid<(nEq-1) ){
20047a419235Sdan     return SQLITE_NOTFOUND;
20051f9c7663Sdrh   }
20067a419235Sdan 
2007dd6e1f19Sdan   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
2008dd6e1f19Sdan   ** below would return the same value.  */
2009fd984b81Sdan   if( nEq>=p->nColumn ){
20107a419235Sdan     *pnRow = 1;
20117a419235Sdan     return SQLITE_OK;
20127a419235Sdan   }
20137a419235Sdan 
2014d66e5794Sdan   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
201587cd9321Sdan   pBuilder->pRec = pRec;
20167a419235Sdan   if( rc!=SQLITE_OK ) return rc;
20177a419235Sdan   if( bOk==0 ) return SQLITE_NOTFOUND;
20187a419235Sdan   pBuilder->nRecValid = nEq;
20197a419235Sdan 
2020b3c02e21Sdan   whereKeyStats(pParse, p, pRec, 0, a);
20214fb48e4eSdrh   WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
20224fb48e4eSdrh                    p->zName, nEq-1, (int)a[1]));
2023faacf17cSdrh   *pnRow = a[1];
20247a419235Sdan 
20250c50fa0fSdrh   return rc;
20260c50fa0fSdrh }
2027175b8f06Sdrh #endif /* SQLITE_ENABLE_STAT4 */
20280c50fa0fSdrh 
2029175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
20300c50fa0fSdrh /*
20310c50fa0fSdrh ** Estimate the number of rows that will be returned based on
20325ac06071Sdrh ** an IN constraint where the right-hand side of the IN operator
20335ac06071Sdrh ** is a list of values.  Example:
20345ac06071Sdrh **
20355ac06071Sdrh **        WHERE x IN (1,2,3,4)
20360c50fa0fSdrh **
20370c50fa0fSdrh ** Write the estimated row count into *pnRow and return SQLITE_OK.
20380c50fa0fSdrh ** If unable to make an estimate, leave *pnRow unchanged and return
20390c50fa0fSdrh ** non-zero.
20400c50fa0fSdrh **
20410c50fa0fSdrh ** This routine can fail if it is unable to load a collating sequence
20420c50fa0fSdrh ** required for string comparison, or if unable to allocate memory
20430c50fa0fSdrh ** for a UTF conversion required for comparison.  The error is stored
20440c50fa0fSdrh ** in the pParse structure.
20450c50fa0fSdrh */
whereInScanEst(Parse * pParse,WhereLoopBuilder * pBuilder,ExprList * pList,tRowcnt * pnRow)2046041e09f1Sdrh static int whereInScanEst(
20470c50fa0fSdrh   Parse *pParse,       /* Parsing & code generating context */
20487a419235Sdan   WhereLoopBuilder *pBuilder,
20490c50fa0fSdrh   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
2050b8a8e8a5Sdrh   tRowcnt *pnRow       /* Write the revised row estimate here */
20510c50fa0fSdrh ){
20527a419235Sdan   Index *p = pBuilder->pNew->u.btree.pIndex;
2053cfc9df76Sdan   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
20547a419235Sdan   int nRecValid = pBuilder->nRecValid;
20555ac06071Sdrh   int rc = SQLITE_OK;     /* Subfunction return code */
2056b8a8e8a5Sdrh   tRowcnt nEst;           /* Number of rows for a single term */
2057b8a8e8a5Sdrh   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
20580c50fa0fSdrh   int i;                  /* Loop counter */
20590c50fa0fSdrh 
20600c50fa0fSdrh   assert( p->aSample!=0 );
2061faacf17cSdrh   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
2062cfc9df76Sdan     nEst = nRow0;
20637a419235Sdan     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
2064faacf17cSdrh     nRowEst += nEst;
20657a419235Sdan     pBuilder->nRecValid = nRecValid;
20660c50fa0fSdrh   }
20677a419235Sdan 
20680c50fa0fSdrh   if( rc==SQLITE_OK ){
2069cfc9df76Sdan     if( nRowEst > nRow0 ) nRowEst = nRow0;
20700c50fa0fSdrh     *pnRow = nRowEst;
20715418b129Sdrh     WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
20720c50fa0fSdrh   }
20737a419235Sdan   assert( pBuilder->nRecValid==nRecValid );
20740c50fa0fSdrh   return rc;
207582759754Sdrh }
2076175b8f06Sdrh #endif /* SQLITE_ENABLE_STAT4 */
207782759754Sdrh 
2078111a6a7dSdrh 
2079d15cb171Sdrh #ifdef WHERETRACE_ENABLED
2080a18f3d27Sdrh /*
2081c90713d3Sdrh ** Print the content of a WhereTerm object
2082c90713d3Sdrh */
sqlite3WhereTermPrint(WhereTerm * pTerm,int iTerm)2083cacdf207Sdrh void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
20840a99ba3bSdrh   if( pTerm==0 ){
20850a99ba3bSdrh     sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
20860a99ba3bSdrh   }else{
2087118efd16Sdrh     char zType[8];
2088c84a4020Sdrh     char zLeft[50];
2089118efd16Sdrh     memcpy(zType, "....", 5);
2090c90713d3Sdrh     if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
2091c90713d3Sdrh     if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
209267a99dbeSdrh     if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) zType[2] = 'L';
2093118efd16Sdrh     if( pTerm->wtFlags & TERM_CODED  ) zType[3] = 'C';
2094c84a4020Sdrh     if( pTerm->eOperator & WO_SINGLE ){
2095220f0d6fSdrh       assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
2096c84a4020Sdrh       sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
209775fa2663Sdrh                        pTerm->leftCursor, pTerm->u.x.leftColumn);
2098c84a4020Sdrh     }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
2099e93986a9Sdrh       sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%llx",
2100c84a4020Sdrh                        pTerm->u.pOrInfo->indexable);
2101c84a4020Sdrh     }else{
2102c84a4020Sdrh       sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
2103c84a4020Sdrh     }
2104fcd49531Sdrh     sqlite3DebugPrintf(
2105118efd16Sdrh        "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
2106118efd16Sdrh        iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
2107118efd16Sdrh     /* The 0x10000 .wheretrace flag causes extra information to be
2108118efd16Sdrh     ** shown about each Term */
21096411d656Sdrh     if( sqlite3WhereTrace & 0x10000 ){
2110118efd16Sdrh       sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
2111118efd16Sdrh         pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
21126411d656Sdrh     }
2113220f0d6fSdrh     if( (pTerm->eOperator & (WO_OR|WO_AND))==0 && pTerm->u.x.iField ){
211475fa2663Sdrh       sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
2115a15a8bc8Sdrh     }
2116d262c2dbSdrh     if( pTerm->iParent>=0 ){
2117d262c2dbSdrh       sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
2118d262c2dbSdrh     }
2119d262c2dbSdrh     sqlite3DebugPrintf("\n");
2120c90713d3Sdrh     sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
2121c90713d3Sdrh   }
21220a99ba3bSdrh }
2123c90713d3Sdrh #endif
2124c90713d3Sdrh 
2125c90713d3Sdrh #ifdef WHERETRACE_ENABLED
2126c90713d3Sdrh /*
2127c84a4020Sdrh ** Show the complete content of a WhereClause
2128c84a4020Sdrh */
sqlite3WhereClausePrint(WhereClause * pWC)2129c84a4020Sdrh void sqlite3WhereClausePrint(WhereClause *pWC){
2130c84a4020Sdrh   int i;
2131c84a4020Sdrh   for(i=0; i<pWC->nTerm; i++){
2132cacdf207Sdrh     sqlite3WhereTermPrint(&pWC->a[i], i);
2133c84a4020Sdrh   }
2134c84a4020Sdrh }
2135c84a4020Sdrh #endif
2136c84a4020Sdrh 
2137c84a4020Sdrh #ifdef WHERETRACE_ENABLED
2138c84a4020Sdrh /*
2139a18f3d27Sdrh ** Print a WhereLoop object for debugging purposes
2140a18f3d27Sdrh */
sqlite3WhereLoopPrint(WhereLoop * p,WhereClause * pWC)2141cacdf207Sdrh void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
2142c1ba2e7aSdrh   WhereInfo *pWInfo = pWC->pWInfo;
214353801efcSdrh   int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
21447601294aSdrh   SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
2145a18f3d27Sdrh   Table *pTab = pItem->pTab;
214653801efcSdrh   Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
2147d15cb171Sdrh   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
214853801efcSdrh                      p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
21496457a353Sdrh   sqlite3DebugPrintf(" %12s",
2150a18f3d27Sdrh                      pItem->zAlias ? pItem->zAlias : pTab->zName);
21515346e95dSdrh   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
2152c1ba2e7aSdrh     const char *zName;
2153c1ba2e7aSdrh     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
2154319f677dSdrh       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
2155319f677dSdrh         int i = sqlite3Strlen30(zName) - 1;
2156319f677dSdrh         while( zName[i]!='_' ) i--;
2157319f677dSdrh         zName += i;
2158319f677dSdrh       }
21596457a353Sdrh       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
2160a18f3d27Sdrh     }else{
21616457a353Sdrh       sqlite3DebugPrintf("%20s","");
2162a18f3d27Sdrh     }
21635346e95dSdrh   }else{
21645346e95dSdrh     char *z;
21655346e95dSdrh     if( p->u.vtab.idxStr ){
216605fbfd82Sdrh       z = sqlite3_mprintf("(%d,\"%s\",%#x)",
21673bd26f05Sdrh                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
21685346e95dSdrh     }else{
21693bd26f05Sdrh       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
21705346e95dSdrh     }
21716457a353Sdrh     sqlite3DebugPrintf(" %-19s", z);
21725346e95dSdrh     sqlite3_free(z);
21735346e95dSdrh   }
2174f3f69ac9Sdrh   if( p->wsFlags & WHERE_SKIPSCAN ){
2175fb82caf0Sdrh     sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
2176f3f69ac9Sdrh   }else{
2177fb82caf0Sdrh     sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm);
2178f3f69ac9Sdrh   }
2179b8a8e8a5Sdrh   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
2180c90713d3Sdrh   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
2181c90713d3Sdrh     int i;
2182c90713d3Sdrh     for(i=0; i<p->nLTerm; i++){
2183cacdf207Sdrh       sqlite3WhereTermPrint(p->aLTerm[i], i);
2184c90713d3Sdrh     }
2185c90713d3Sdrh   }
2186a18f3d27Sdrh }
2187a18f3d27Sdrh #endif
2188a18f3d27Sdrh 
2189f1b5f5b8Sdrh /*
21904efc9298Sdrh ** Convert bulk memory into a valid WhereLoop that can be passed
21914efc9298Sdrh ** to whereLoopClear harmlessly.
21925346e95dSdrh */
whereLoopInit(WhereLoop * p)21934efc9298Sdrh static void whereLoopInit(WhereLoop *p){
21944efc9298Sdrh   p->aLTerm = p->aLTermSpace;
21954efc9298Sdrh   p->nLTerm = 0;
21964efc9298Sdrh   p->nLSlot = ArraySize(p->aLTermSpace);
21974efc9298Sdrh   p->wsFlags = 0;
21984efc9298Sdrh }
21994efc9298Sdrh 
22004efc9298Sdrh /*
22014efc9298Sdrh ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
22024efc9298Sdrh */
whereLoopClearUnion(sqlite3 * db,WhereLoop * p)22034efc9298Sdrh static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
2204986b3879Sdrh   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
220513e11b43Sdrh     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
220613e11b43Sdrh       sqlite3_free(p->u.vtab.idxStr);
22075346e95dSdrh       p->u.vtab.needFree = 0;
22085346e95dSdrh       p->u.vtab.idxStr = 0;
2209986b3879Sdrh     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
22106fa978daSdrh       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
2211dbd6a7dcSdrh       sqlite3DbFreeNN(db, p->u.btree.pIndex);
22126fa978daSdrh       p->u.btree.pIndex = 0;
22135346e95dSdrh     }
22145346e95dSdrh   }
221513e11b43Sdrh }
22164efc9298Sdrh 
22174efc9298Sdrh /*
221874879e13Sdrh ** Deallocate internal memory used by a WhereLoop object.  Leave the
221974879e13Sdrh ** object in an initialized state, as if it had been newly allocated.
22204efc9298Sdrh */
whereLoopClear(sqlite3 * db,WhereLoop * p)22214efc9298Sdrh static void whereLoopClear(sqlite3 *db, WhereLoop *p){
222274879e13Sdrh   if( p->aLTerm!=p->aLTermSpace ){
222374879e13Sdrh     sqlite3DbFreeNN(db, p->aLTerm);
222474879e13Sdrh     p->aLTerm = p->aLTermSpace;
222574879e13Sdrh     p->nLSlot = ArraySize(p->aLTermSpace);
222674879e13Sdrh   }
22274efc9298Sdrh   whereLoopClearUnion(db, p);
222874879e13Sdrh   p->nLTerm = 0;
222974879e13Sdrh   p->wsFlags = 0;
22304efc9298Sdrh }
22314efc9298Sdrh 
22324efc9298Sdrh /*
22334efc9298Sdrh ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
22344efc9298Sdrh */
whereLoopResize(sqlite3 * db,WhereLoop * p,int n)22354efc9298Sdrh static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
22364efc9298Sdrh   WhereTerm **paNew;
22374efc9298Sdrh   if( p->nLSlot>=n ) return SQLITE_OK;
22384efc9298Sdrh   n = (n+7)&~7;
2239575fad65Sdrh   paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
2240fad3039cSmistachkin   if( paNew==0 ) return SQLITE_NOMEM_BKPT;
22414efc9298Sdrh   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
2242dbd6a7dcSdrh   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
22434efc9298Sdrh   p->aLTerm = paNew;
22444efc9298Sdrh   p->nLSlot = n;
22454efc9298Sdrh   return SQLITE_OK;
22464efc9298Sdrh }
22474efc9298Sdrh 
22484efc9298Sdrh /*
22494efc9298Sdrh ** Transfer content from the second pLoop into the first.
22504efc9298Sdrh */
whereLoopXfer(sqlite3 * db,WhereLoop * pTo,WhereLoop * pFrom)22514efc9298Sdrh static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
22524efc9298Sdrh   whereLoopClearUnion(db, pTo);
225374879e13Sdrh   if( pFrom->nLTerm > pTo->nLSlot
225474879e13Sdrh    && whereLoopResize(db, pTo, pFrom->nLTerm)
225574879e13Sdrh   ){
225682404315Sdrh     memset(pTo, 0, WHERE_LOOP_XFER_SZ);
2257fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
22580d31dc37Sdrh   }
2259a2014159Sdrh   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
22604efc9298Sdrh   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
22614efc9298Sdrh   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
22624efc9298Sdrh     pFrom->u.vtab.needFree = 0;
2263986b3879Sdrh   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
22644efc9298Sdrh     pFrom->u.btree.pIndex = 0;
22654efc9298Sdrh   }
22664efc9298Sdrh   return SQLITE_OK;
22674efc9298Sdrh }
22684efc9298Sdrh 
22695346e95dSdrh /*
2270f1b5f5b8Sdrh ** Delete a WhereLoop object
2271f1b5f5b8Sdrh */
whereLoopDelete(sqlite3 * db,WhereLoop * p)2272f1b5f5b8Sdrh static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
227341ce47c4Sdrh   assert( db!=0 );
22745346e95dSdrh   whereLoopClear(db, p);
227541ce47c4Sdrh   sqlite3DbNNFreeNN(db, p);
2276f1b5f5b8Sdrh }
227784bfda41Sdrh 
22789eff6167Sdrh /*
22799eff6167Sdrh ** Free a WhereInfo structure
22809eff6167Sdrh */
whereInfoFree(sqlite3 * db,WhereInfo * pWInfo)228110fe840eSdrh static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
22829d9c41e2Sdrh   assert( pWInfo!=0 );
228341ce47c4Sdrh   assert( db!=0 );
22846c1f4ef2Sdrh   sqlite3WhereClauseClear(&pWInfo->sWC);
2285f1b5f5b8Sdrh   while( pWInfo->pLoops ){
2286f1b5f5b8Sdrh     WhereLoop *p = pWInfo->pLoops;
2287f1b5f5b8Sdrh     pWInfo->pLoops = p->pNextLoop;
2288f1b5f5b8Sdrh     whereLoopDelete(db, p);
2289f1b5f5b8Sdrh   }
2290f8bdcfa3Sdrh   while( pWInfo->pMemToFree ){
2291f8bdcfa3Sdrh     WhereMemBlock *pNext = pWInfo->pMemToFree->pNext;
229241ce47c4Sdrh     sqlite3DbNNFreeNN(db, pWInfo->pMemToFree);
2293f8bdcfa3Sdrh     pWInfo->pMemToFree = pNext;
2294f8bdcfa3Sdrh   }
229541ce47c4Sdrh   sqlite3DbNNFreeNN(db, pWInfo);
22969eff6167Sdrh }
22979eff6167Sdrh 
2298f1b5f5b8Sdrh /*
2299e0de876eSdrh ** Return TRUE if all of the following are true:
2300b355c2ccSdrh **
2301748d8b9cSdan **   (1)  X has the same or lower cost, or returns the same or fewer rows,
2302748d8b9cSdan **        than Y.
2303989d7278Sdrh **   (2)  X uses fewer WHERE clause terms than Y
230447b1d68fSdrh **   (3)  Every WHERE clause term used by X is also used by Y
230547b1d68fSdrh **   (4)  X skips at least as many columns as Y
230647b1d68fSdrh **   (5)  If X is a covering index, than Y is too
2307b355c2ccSdrh **
230847b1d68fSdrh ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
2309b355c2ccSdrh ** If X is a proper subset of Y then Y is a better choice and ought
2310b355c2ccSdrh ** to have a lower cost.  This routine returns TRUE when that cost
231147b1d68fSdrh ** relationship is inverted and needs to be adjusted.  Constraint (4)
2312e0de876eSdrh ** was added because if X uses skip-scan less than Y it still might
2313989d7278Sdrh ** deserve a lower cost even if it is a proper subset of Y.  Constraint (5)
2314989d7278Sdrh ** was added because a covering index probably deserves to have a lower cost
2315989d7278Sdrh ** than a non-covering index even if it is a proper subset.
23163fb183d2Sdrh */
whereLoopCheaperProperSubset(const WhereLoop * pX,const WhereLoop * pY)2317b355c2ccSdrh static int whereLoopCheaperProperSubset(
2318b355c2ccSdrh   const WhereLoop *pX,       /* First WhereLoop to compare */
2319b355c2ccSdrh   const WhereLoop *pY        /* Compare against this WhereLoop */
2320b355c2ccSdrh ){
23213fb183d2Sdrh   int i, j;
2322c8bbce1eSdrh   if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
2323c8bbce1eSdrh     return 0; /* X is not a subset of Y */
2324c8bbce1eSdrh   }
2325748d8b9cSdan   if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0;
2326e0de876eSdrh   if( pY->nSkip > pX->nSkip ) return 0;
23279ee8810bSdrh   for(i=pX->nLTerm-1; i>=0; i--){
2328c8bbce1eSdrh     if( pX->aLTerm[i]==0 ) continue;
2329b355c2ccSdrh     for(j=pY->nLTerm-1; j>=0; j--){
2330b355c2ccSdrh       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
23313fb183d2Sdrh     }
2332b355c2ccSdrh     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
2333b355c2ccSdrh   }
233447b1d68fSdrh   if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
233547b1d68fSdrh    && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
233647b1d68fSdrh     return 0;  /* Constraint (5) */
233747b1d68fSdrh   }
2338b355c2ccSdrh   return 1;  /* All conditions meet */
23393fb183d2Sdrh }
23403fb183d2Sdrh 
23413fb183d2Sdrh /*
2342748d8b9cSdan ** Try to adjust the cost and number of output rows of WhereLoop pTemplate
2343748d8b9cSdan ** upwards or downwards so that:
234453cd10afSdrh **
23453fb183d2Sdrh **   (1) pTemplate costs less than any other WhereLoops that are a proper
23463fb183d2Sdrh **       subset of pTemplate
234753cd10afSdrh **
23483fb183d2Sdrh **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
23493fb183d2Sdrh **       is a proper subset.
235053cd10afSdrh **
23513fb183d2Sdrh ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
23523fb183d2Sdrh ** WHERE clause terms than Y and that every WHERE clause term used by X is
23533fb183d2Sdrh ** also used by Y.
235453cd10afSdrh */
whereLoopAdjustCost(const WhereLoop * p,WhereLoop * pTemplate)235553cd10afSdrh static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
235653cd10afSdrh   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
235753cd10afSdrh   for(; p; p=p->pNextLoop){
23583fb183d2Sdrh     if( p->iTab!=pTemplate->iTab ) continue;
23593fb183d2Sdrh     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
2360b355c2ccSdrh     if( whereLoopCheaperProperSubset(p, pTemplate) ){
2361b355c2ccSdrh       /* Adjust pTemplate cost downward so that it is cheaper than its
2362e0de876eSdrh       ** subset p. */
23631b131b7aSdrh       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2364748d8b9cSdan                        pTemplate->rRun, pTemplate->nOut,
2365748d8b9cSdan                        MIN(p->rRun, pTemplate->rRun),
2366748d8b9cSdan                        MIN(p->nOut - 1, pTemplate->nOut)));
2367748d8b9cSdan       pTemplate->rRun = MIN(p->rRun, pTemplate->rRun);
2368748d8b9cSdan       pTemplate->nOut = MIN(p->nOut - 1, pTemplate->nOut);
2369b355c2ccSdrh     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
2370b355c2ccSdrh       /* Adjust pTemplate cost upward so that it is costlier than p since
2371b355c2ccSdrh       ** pTemplate is a proper subset of p */
23721b131b7aSdrh       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
2373748d8b9cSdan                        pTemplate->rRun, pTemplate->nOut,
2374748d8b9cSdan                        MAX(p->rRun, pTemplate->rRun),
2375748d8b9cSdan                        MAX(p->nOut + 1, pTemplate->nOut)));
2376748d8b9cSdan       pTemplate->rRun = MAX(p->rRun, pTemplate->rRun);
2377748d8b9cSdan       pTemplate->nOut = MAX(p->nOut + 1, pTemplate->nOut);
237853cd10afSdrh     }
237953cd10afSdrh   }
238053cd10afSdrh }
238153cd10afSdrh 
238253cd10afSdrh /*
23837a4b1642Sdrh ** Search the list of WhereLoops in *ppPrev looking for one that can be
2384bcbb0665Sdrh ** replaced by pTemplate.
2385f1b5f5b8Sdrh **
2386bcbb0665Sdrh ** Return NULL if pTemplate does not belong on the WhereLoop list.
2387bcbb0665Sdrh ** In other words if pTemplate ought to be dropped from further consideration.
238823f98daaSdrh **
2389bcbb0665Sdrh ** If pX is a WhereLoop that pTemplate can replace, then return the
23907a4b1642Sdrh ** link that points to pX.
239123f98daaSdrh **
2392bcbb0665Sdrh ** If pTemplate cannot replace any existing element of the list but needs
2393bcbb0665Sdrh ** to be added to the list as a new entry, then return a pointer to the
2394bcbb0665Sdrh ** tail of the list.
2395f1b5f5b8Sdrh */
whereLoopFindLesser(WhereLoop ** ppPrev,const WhereLoop * pTemplate)23967a4b1642Sdrh static WhereLoop **whereLoopFindLesser(
23977a4b1642Sdrh   WhereLoop **ppPrev,
23987a4b1642Sdrh   const WhereLoop *pTemplate
23997a4b1642Sdrh ){
24007a4b1642Sdrh   WhereLoop *p;
24017a4b1642Sdrh   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
2402dbb80234Sdrh     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
2403dbb80234Sdrh       /* If either the iTab or iSortIdx values for two WhereLoop are different
2404dbb80234Sdrh       ** then those WhereLoops need to be considered separately.  Neither is
2405dbb80234Sdrh       ** a candidate to replace the other. */
2406dbb80234Sdrh       continue;
2407dbb80234Sdrh     }
2408dbb80234Sdrh     /* In the current implementation, the rSetup value is either zero
2409dbb80234Sdrh     ** or the cost of building an automatic index (NlogN) and the NlogN
2410dbb80234Sdrh     ** is the same for compatible WhereLoops. */
2411dbb80234Sdrh     assert( p->rSetup==0 || pTemplate->rSetup==0
2412dbb80234Sdrh                  || p->rSetup==pTemplate->rSetup );
2413dbb80234Sdrh 
2414dbb80234Sdrh     /* whereLoopAddBtree() always generates and inserts the automatic index
2415dbb80234Sdrh     ** case first.  Hence compatible candidate WhereLoops never have a larger
2416dbb80234Sdrh     ** rSetup. Call this SETUP-INVARIANT */
2417dbb80234Sdrh     assert( p->rSetup>=pTemplate->rSetup );
2418dbb80234Sdrh 
2419dabe36d9Sdrh     /* Any loop using an appliation-defined index (or PRIMARY KEY or
2420dabe36d9Sdrh     ** UNIQUE constraint) with one or more == constraints is better
242170273d0bSdan     ** than an automatic index. Unless it is a skip-scan. */
2422dabe36d9Sdrh     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
242370273d0bSdan      && (pTemplate->nSkip)==0
2424dabe36d9Sdrh      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
2425dabe36d9Sdrh      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
2426dabe36d9Sdrh      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
2427dabe36d9Sdrh     ){
2428dabe36d9Sdrh       break;
2429dabe36d9Sdrh     }
2430dabe36d9Sdrh 
243153cd10afSdrh     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
243253cd10afSdrh     ** discarded.  WhereLoop p is better if:
243353cd10afSdrh     **   (1)  p has no more dependencies than pTemplate, and
243453cd10afSdrh     **   (2)  p has an equal or lower cost than pTemplate
243553cd10afSdrh     */
243653cd10afSdrh     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
243753cd10afSdrh      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
243853cd10afSdrh      && p->rRun<=pTemplate->rRun                      /* (2b) */
243953cd10afSdrh      && p->nOut<=pTemplate->nOut                      /* (2c) */
2440cd0f407cSdrh     ){
244153cd10afSdrh       return 0;  /* Discard pTemplate */
2442f1b5f5b8Sdrh     }
244353cd10afSdrh 
244453cd10afSdrh     /* If pTemplate is always better than p, then cause p to be overwritten
244553cd10afSdrh     ** with pTemplate.  pTemplate is better than p if:
244653cd10afSdrh     **   (1)  pTemplate has no more dependences than p, and
244753cd10afSdrh     **   (2)  pTemplate has an equal or lower cost than p.
244853cd10afSdrh     */
244953cd10afSdrh     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
245053cd10afSdrh      && p->rRun>=pTemplate->rRun                             /* (2a) */
245153cd10afSdrh      && p->nOut>=pTemplate->nOut                             /* (2b) */
2452f1b5f5b8Sdrh     ){
2453add5ce30Sdrh       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
245453cd10afSdrh       break;   /* Cause p to be overwritten by pTemplate */
2455f1b5f5b8Sdrh     }
2456f1b5f5b8Sdrh   }
24577a4b1642Sdrh   return ppPrev;
24587a4b1642Sdrh }
24597a4b1642Sdrh 
24607a4b1642Sdrh /*
246194a11211Sdrh ** Insert or replace a WhereLoop entry using the template supplied.
246294a11211Sdrh **
246394a11211Sdrh ** An existing WhereLoop entry might be overwritten if the new template
246494a11211Sdrh ** is better and has fewer dependencies.  Or the template will be ignored
246594a11211Sdrh ** and no insert will occur if an existing WhereLoop is faster and has
246694a11211Sdrh ** fewer dependencies than the template.  Otherwise a new WhereLoop is
2467b3bce662Sdanielk1977 ** added based on the template.
246894a11211Sdrh **
24697a4b1642Sdrh ** If pBuilder->pOrSet is not NULL then we care about only the
247094a11211Sdrh ** prerequisites and rRun and nOut costs of the N best loops.  That
247194a11211Sdrh ** information is gathered in the pBuilder->pOrSet object.  This special
247294a11211Sdrh ** processing mode is used only for OR clause processing.
2473b3bce662Sdanielk1977 **
247494a11211Sdrh ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
2475b3bce662Sdanielk1977 ** still might overwrite similar loops with the new template if the
247653cd10afSdrh ** new template is better.  Loops may be overwritten if the following
247794a11211Sdrh ** conditions are met:
247894a11211Sdrh **
247994a11211Sdrh **    (1)  They have the same iTab.
248094a11211Sdrh **    (2)  They have the same iSortIdx.
248194a11211Sdrh **    (3)  The template has same or fewer dependencies than the current loop
248294a11211Sdrh **    (4)  The template has the same or lower cost than the current loop
248394a11211Sdrh */
whereLoopInsert(WhereLoopBuilder * pBuilder,WhereLoop * pTemplate)248494a11211Sdrh static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
24857a4b1642Sdrh   WhereLoop **ppPrev, *p;
248694a11211Sdrh   WhereInfo *pWInfo = pBuilder->pWInfo;
248794a11211Sdrh   sqlite3 *db = pWInfo->pParse->db;
2488bacbbccdSdrh   int rc;
248994a11211Sdrh 
2490fc9098a4Sdrh   /* Stop the search once we hit the query planner search limit */
24912c3ba949Sdrh   if( pBuilder->iPlanLimit==0 ){
24922c3ba949Sdrh     WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
24932c3ba949Sdrh     if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
24942c3ba949Sdrh     return SQLITE_DONE;
24952c3ba949Sdrh   }
2496fc9098a4Sdrh   pBuilder->iPlanLimit--;
2497fc9098a4Sdrh 
249851f2b171Sdan   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
249951f2b171Sdan 
250094a11211Sdrh   /* If pBuilder->pOrSet is defined, then only keep track of the costs
250194a11211Sdrh   ** and prereqs.
250294a11211Sdrh   */
250394a11211Sdrh   if( pBuilder->pOrSet!=0 ){
25042dc29293Sdrh     if( pTemplate->nLTerm ){
250594a11211Sdrh #if WHERETRACE_ENABLED
250694a11211Sdrh       u16 n = pBuilder->pOrSet->n;
250794a11211Sdrh       int x =
250894a11211Sdrh #endif
250994a11211Sdrh       whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
251094a11211Sdrh                                     pTemplate->nOut);
251194a11211Sdrh #if WHERETRACE_ENABLED /* 0x8 */
251294a11211Sdrh       if( sqlite3WhereTrace & 0x8 ){
2513b3bce662Sdanielk1977         sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
2514cacdf207Sdrh         sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2515b3bce662Sdanielk1977       }
251694a11211Sdrh #endif
25172dc29293Sdrh     }
2518b3bce662Sdanielk1977     return SQLITE_OK;
25199012bcbcSdrh   }
252094a11211Sdrh 
25217a4b1642Sdrh   /* Look for an existing WhereLoop to replace with pTemplate
252251669863Sdrh   */
25237a4b1642Sdrh   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
25247a4b1642Sdrh 
25257a4b1642Sdrh   if( ppPrev==0 ){
25267a4b1642Sdrh     /* There already exists a WhereLoop on the list that is better
25277a4b1642Sdrh     ** than pTemplate, so just ignore pTemplate */
25287a4b1642Sdrh #if WHERETRACE_ENABLED /* 0x8 */
25297a4b1642Sdrh     if( sqlite3WhereTrace & 0x8 ){
25309a7b41d7Sdrh       sqlite3DebugPrintf("   skip: ");
2531cacdf207Sdrh       sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2532f1b5f5b8Sdrh     }
25337a4b1642Sdrh #endif
25347a4b1642Sdrh     return SQLITE_OK;
2535f1b5f5b8Sdrh   }else{
25367a4b1642Sdrh     p = *ppPrev;
2537f1b5f5b8Sdrh   }
2538f1b5f5b8Sdrh 
2539f1b5f5b8Sdrh   /* If we reach this point it means that either p[] should be overwritten
2540f1b5f5b8Sdrh   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
2541f1b5f5b8Sdrh   ** WhereLoop and insert it.
2542f1b5f5b8Sdrh   */
2543989578e1Sdrh #if WHERETRACE_ENABLED /* 0x8 */
2544ae70cf18Sdrh   if( sqlite3WhereTrace & 0x8 ){
2545ae70cf18Sdrh     if( p!=0 ){
25469a7b41d7Sdrh       sqlite3DebugPrintf("replace: ");
2547cacdf207Sdrh       sqlite3WhereLoopPrint(p, pBuilder->pWC);
2548bcbb0665Sdrh       sqlite3DebugPrintf("   with: ");
2549bcbb0665Sdrh     }else{
25509a7b41d7Sdrh       sqlite3DebugPrintf("    add: ");
2551bcbb0665Sdrh     }
2552cacdf207Sdrh     sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
2553ae70cf18Sdrh   }
2554ae70cf18Sdrh #endif
2555f1b5f5b8Sdrh   if( p==0 ){
25567a4b1642Sdrh     /* Allocate a new WhereLoop to add to the end of the list */
2557575fad65Sdrh     *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
2558fad3039cSmistachkin     if( p==0 ) return SQLITE_NOMEM_BKPT;
25594efc9298Sdrh     whereLoopInit(p);
25607a4b1642Sdrh     p->pNextLoop = 0;
25617a4b1642Sdrh   }else{
25627a4b1642Sdrh     /* We will be overwriting WhereLoop p[].  But before we do, first
25637a4b1642Sdrh     ** go through the rest of the list and delete any other entries besides
25647a4b1642Sdrh     ** p[] that are also supplated by pTemplate */
25657a4b1642Sdrh     WhereLoop **ppTail = &p->pNextLoop;
25667a4b1642Sdrh     WhereLoop *pToDel;
25677a4b1642Sdrh     while( *ppTail ){
25687a4b1642Sdrh       ppTail = whereLoopFindLesser(ppTail, pTemplate);
2569dabe36d9Sdrh       if( ppTail==0 ) break;
25707a4b1642Sdrh       pToDel = *ppTail;
25717a4b1642Sdrh       if( pToDel==0 ) break;
25727a4b1642Sdrh       *ppTail = pToDel->pNextLoop;
25737a4b1642Sdrh #if WHERETRACE_ENABLED /* 0x8 */
25747a4b1642Sdrh       if( sqlite3WhereTrace & 0x8 ){
25759a7b41d7Sdrh         sqlite3DebugPrintf(" delete: ");
2576cacdf207Sdrh         sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
25777a4b1642Sdrh       }
25787a4b1642Sdrh #endif
25797a4b1642Sdrh       whereLoopDelete(db, pToDel);
25807a4b1642Sdrh     }
2581f1b5f5b8Sdrh   }
2582bacbbccdSdrh   rc = whereLoopXfer(db, p, pTemplate);
25835346e95dSdrh   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
2584ef866376Sdrh     Index *pIndex = p->u.btree.pIndex;
25855f913ecbSdrh     if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
2586cf8fa7a6Sdrh       p->u.btree.pIndex = 0;
2587cf8fa7a6Sdrh     }
25885346e95dSdrh   }
2589bacbbccdSdrh   return rc;
2590f1b5f5b8Sdrh }
2591f1b5f5b8Sdrh 
2592f1b5f5b8Sdrh /*
2593cca9f3d2Sdrh ** Adjust the WhereLoop.nOut value downward to account for terms of the
2594cca9f3d2Sdrh ** WHERE clause that reference the loop but which are not used by an
2595cca9f3d2Sdrh ** index.
25967a1bca7eSdrh *
25977a1bca7eSdrh ** For every WHERE clause term that is not used by the index
25987a1bca7eSdrh ** and which has a truth probability assigned by one of the likelihood(),
25997a1bca7eSdrh ** likely(), or unlikely() SQL functions, reduce the estimated number
26007a1bca7eSdrh ** of output rows by the probability specified.
2601cca9f3d2Sdrh **
26027a1bca7eSdrh ** TUNING:  For every WHERE clause term that is not used by the index
26037a1bca7eSdrh ** and which does not have an assigned truth probability, heuristics
26047a1bca7eSdrh ** described below are used to try to estimate the truth probability.
26057a1bca7eSdrh ** TODO --> Perhaps this is something that could be improved by better
26067a1bca7eSdrh ** table statistics.
26077a1bca7eSdrh **
2608ab4624d0Sdrh ** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
2609ab4624d0Sdrh ** value corresponds to -1 in LogEst notation, so this means decrement
26107a1bca7eSdrh ** the WhereLoop.nOut field for every such WHERE clause term.
26117a1bca7eSdrh **
26127a1bca7eSdrh ** Heuristic 2:  If there exists one or more WHERE clause terms of the
26137a1bca7eSdrh ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
26147a1bca7eSdrh ** final output row estimate is no greater than 1/4 of the total number
26157a1bca7eSdrh ** of rows in the table.  In other words, assume that x==EXPR will filter
26167a1bca7eSdrh ** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
26177a1bca7eSdrh ** "x" column is boolean or else -1 or 0 or 1 is a common default value
26187a1bca7eSdrh ** on the "x" column and so in that case only cap the output row estimate
26197a1bca7eSdrh ** at 1/2 instead of 1/4.
2620cca9f3d2Sdrh */
whereLoopOutputAdjust(WhereClause * pWC,WhereLoop * pLoop,LogEst nRow)2621d8b77e20Sdrh static void whereLoopOutputAdjust(
2622d8b77e20Sdrh   WhereClause *pWC,      /* The WHERE clause */
2623d8b77e20Sdrh   WhereLoop *pLoop,      /* The loop to adjust downward */
2624d8b77e20Sdrh   LogEst nRow            /* Number of rows in the entire table */
2625d8b77e20Sdrh ){
26267d9e7d82Sdrh   WhereTerm *pTerm, *pX;
2627cca9f3d2Sdrh   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
2628aa16c603Sdrh   int i, j;
26297a1bca7eSdrh   LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
2630add5ce30Sdrh 
2631a3898250Sdrh   assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
2632132f96fcSdrh   for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){
263355f66b34Sdrh     assert( pTerm!=0 );
2634cca9f3d2Sdrh     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
2635132f96fcSdrh     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
2636132f96fcSdrh     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) continue;
26377d9e7d82Sdrh     for(j=pLoop->nLTerm-1; j>=0; j--){
26387d9e7d82Sdrh       pX = pLoop->aLTerm[j];
2639d2447447Sdrh       if( pX==0 ) continue;
26407d9e7d82Sdrh       if( pX==pTerm ) break;
26417d9e7d82Sdrh       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
2642cca9f3d2Sdrh     }
2643aa9933c1Sdan     if( j<0 ){
2644fb82caf0Sdrh       if( pLoop->maskSelf==pTerm->prereqAll ){
26457e910f64Sdrh         /* If there are extra terms in the WHERE clause not used by an index
26467e910f64Sdrh         ** that depend only on the table being scanned, and that will tend to
26477e910f64Sdrh         ** cause many rows to be omitted, then mark that table as
2648be341502Sdrh         ** "self-culling".
2649be341502Sdrh         **
2650be341502Sdrh         ** 2022-03-24:  Self-culling only applies if either the extra terms
2651be341502Sdrh         ** are straight comparison operators that are non-true with NULL
2652a76ac88aSdrh         ** operand, or if the loop is not an OUTER JOIN.
2653be341502Sdrh         */
2654be341502Sdrh         if( (pTerm->eOperator & 0x3f)!=0
2655a76ac88aSdrh          || (pWC->pWInfo->pTabList->a[pLoop->iTab].fg.jointype
2656a76ac88aSdrh                   & (JT_LEFT|JT_LTORJ))==0
2657be341502Sdrh         ){
26587e910f64Sdrh           pLoop->wsFlags |= WHERE_SELFCULL;
2659fb82caf0Sdrh         }
2660be341502Sdrh       }
2661d8b77e20Sdrh       if( pTerm->truthProb<=0 ){
26627a1bca7eSdrh         /* If a truth probability is specified using the likelihood() hints,
26637a1bca7eSdrh         ** then use the probability provided by the application. */
2664d8b77e20Sdrh         pLoop->nOut += pTerm->truthProb;
2665d8b77e20Sdrh       }else{
26667a1bca7eSdrh         /* In the absence of explicit truth probabilities, use heuristics to
26677a1bca7eSdrh         ** guess a reasonable truth probability. */
2668d8b77e20Sdrh         pLoop->nOut--;
2669f06cdde2Sdrh         if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
2670f06cdde2Sdrh          && (pTerm->wtFlags & TERM_HIGHTRUTH)==0  /* tag-20200224-1 */
2671f06cdde2Sdrh         ){
26727a1bca7eSdrh           Expr *pRight = pTerm->pExpr->pRight;
2673aa16c603Sdrh           int k = 0;
2674e0cc3c29Sdrh           testcase( pTerm->pExpr->op==TK_IS );
26757a1bca7eSdrh           if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
26767a1bca7eSdrh             k = 10;
26777a1bca7eSdrh           }else{
2678f06cdde2Sdrh             k = 20;
26797a1bca7eSdrh           }
268089efac94Sdrh           if( iReduce<k ){
268189efac94Sdrh             pTerm->wtFlags |= TERM_HEURTRUTH;
268289efac94Sdrh             iReduce = k;
268389efac94Sdrh           }
2684aa9933c1Sdan         }
2685cca9f3d2Sdrh       }
2686cca9f3d2Sdrh     }
2687d8b77e20Sdrh   }
2688fb82caf0Sdrh   if( pLoop->nOut > nRow-iReduce ){
2689fb82caf0Sdrh     pLoop->nOut = nRow - iReduce;
2690fb82caf0Sdrh   }
2691d8b77e20Sdrh }
2692cca9f3d2Sdrh 
2693cca9f3d2Sdrh /*
269471c57db0Sdan ** Term pTerm is a vector range comparison operation. The first comparison
2695553168c7Sdan ** in the vector can be optimized using column nEq of the index. This
2696553168c7Sdan ** function returns the total number of vector elements that can be used
2697553168c7Sdan ** as part of the range comparison.
2698553168c7Sdan **
2699553168c7Sdan ** For example, if the query is:
2700553168c7Sdan **
2701553168c7Sdan **   WHERE a = ? AND (b, c, d) > (?, ?, ?)
2702553168c7Sdan **
2703553168c7Sdan ** and the index:
2704553168c7Sdan **
2705553168c7Sdan **   CREATE INDEX ... ON (a, b, c, d, e)
2706553168c7Sdan **
2707553168c7Sdan ** then this function would be invoked with nEq=1. The value returned in
2708553168c7Sdan ** this case is 3.
270971c57db0Sdan */
whereRangeVectorLen(Parse * pParse,int iCur,Index * pIdx,int nEq,WhereTerm * pTerm)2710320d4c30Sdan static int whereRangeVectorLen(
271164bcb8cfSdrh   Parse *pParse,       /* Parsing context */
271264bcb8cfSdrh   int iCur,            /* Cursor open on pIdx */
271364bcb8cfSdrh   Index *pIdx,         /* The index to be used for a inequality constraint */
271464bcb8cfSdrh   int nEq,             /* Number of prior equality constraints on same index */
271564bcb8cfSdrh   WhereTerm *pTerm     /* The vector inequality constraint */
271671c57db0Sdan ){
271771c57db0Sdan   int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
271871c57db0Sdan   int i;
271971c57db0Sdan 
272071c57db0Sdan   nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
272171c57db0Sdan   for(i=1; i<nCmp; i++){
272271c57db0Sdan     /* Test if comparison i of pTerm is compatible with column (i+nEq)
272371c57db0Sdan     ** of the index. If not, exit the loop.  */
272471c57db0Sdan     char aff;                     /* Comparison affinity */
272571c57db0Sdan     char idxaff = 0;              /* Indexed columns affinity */
272671c57db0Sdan     CollSeq *pColl;               /* Comparison collation sequence */
2727a4eeccdfSdrh     Expr *pLhs, *pRhs;
2728a4eeccdfSdrh 
2729a4eeccdfSdrh     assert( ExprUseXList(pTerm->pExpr->pLeft) );
2730a4eeccdfSdrh     pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
2731a4eeccdfSdrh     pRhs = pTerm->pExpr->pRight;
2732a4eeccdfSdrh     if( ExprUseXSelect(pRhs) ){
273371c57db0Sdan       pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
273471c57db0Sdan     }else{
273571c57db0Sdan       pRhs = pRhs->x.pList->a[i].pExpr;
273671c57db0Sdan     }
273771c57db0Sdan 
273871c57db0Sdan     /* Check that the LHS of the comparison is a column reference to
2739d05a7144Sdan     ** the right column of the right source table. And that the sort
2740d05a7144Sdan     ** order of the index column is the same as the sort order of the
2741d05a7144Sdan     ** leftmost index column.  */
274271c57db0Sdan     if( pLhs->op!=TK_COLUMN
274371c57db0Sdan      || pLhs->iTable!=iCur
274471c57db0Sdan      || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
27452c628ea9Sdan      || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
274671c57db0Sdan     ){
274771c57db0Sdan       break;
274871c57db0Sdan     }
274971c57db0Sdan 
27500c36fca0Sdrh     testcase( pLhs->iColumn==XN_ROWID );
275171c57db0Sdan     aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
27520dfa4f6fSdrh     idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
275371c57db0Sdan     if( aff!=idxaff ) break;
275471c57db0Sdan 
275571c57db0Sdan     pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
27560dfa4f6fSdrh     if( pColl==0 ) break;
275764bcb8cfSdrh     if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
275871c57db0Sdan   }
275971c57db0Sdan   return i;
276071c57db0Sdan }
276171c57db0Sdan 
276271c57db0Sdan /*
2763dbd9486dSdrh ** Adjust the cost C by the costMult facter T.  This only occurs if
2764dbd9486dSdrh ** compiled with -DSQLITE_ENABLE_COSTMULT
2765dbd9486dSdrh */
2766dbd9486dSdrh #ifdef SQLITE_ENABLE_COSTMULT
2767dbd9486dSdrh # define ApplyCostMultiplier(C,T)  C += T
2768dbd9486dSdrh #else
2769dbd9486dSdrh # define ApplyCostMultiplier(C,T)
2770dbd9486dSdrh #endif
2771dbd9486dSdrh 
2772dbd9486dSdrh /*
27734a6b8a05Sdan ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
27744a6b8a05Sdan ** index pIndex. Try to match one more.
27754a6b8a05Sdan **
27764a6b8a05Sdan ** When this function is called, pBuilder->pNew->nOut contains the
27774a6b8a05Sdan ** number of rows expected to be visited by filtering using the nEq
27784a6b8a05Sdan ** terms only. If it is modified, this value is restored before this
27794a6b8a05Sdan ** function returns.
27801c8148ffSdrh **
27815f913ecbSdrh ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
27825f913ecbSdrh ** a fake index used for the INTEGER PRIMARY KEY.
27831c8148ffSdrh */
whereLoopAddBtreeIndex(WhereLoopBuilder * pBuilder,SrcItem * pSrc,Index * pProbe,LogEst nInMul)27845346e95dSdrh static int whereLoopAddBtreeIndex(
27851c8148ffSdrh   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
27867601294aSdrh   SrcItem *pSrc,                  /* FROM clause term being analyzed */
27871c8148ffSdrh   Index *pProbe,                  /* An index on pSrc */
2788bf539c4dSdrh   LogEst nInMul                   /* log(Number of iterations due to IN) */
27891c8148ffSdrh ){
279070d18344Sdrh   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
279170d18344Sdrh   Parse *pParse = pWInfo->pParse;        /* Parsing context */
279270d18344Sdrh   sqlite3 *db = pParse->db;       /* Database connection malloc context */
27931c8148ffSdrh   WhereLoop *pNew;                /* Template WhereLoop under construction */
27941c8148ffSdrh   WhereTerm *pTerm;               /* A WhereTerm under consideration */
279543fe25fcSdrh   int opMask;                     /* Valid operators for constraints */
27961c8148ffSdrh   WhereScan scan;                 /* Iterator for WHERE terms */
27974efc9298Sdrh   Bitmask saved_prereq;           /* Original value of pNew->prereq */
27984efc9298Sdrh   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
2799cd8629e4Sdrh   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
280071c57db0Sdan   u16 saved_nBtm;                 /* Original value of pNew->u.btree.nBtm */
280171c57db0Sdan   u16 saved_nTop;                 /* Original value of pNew->u.btree.nTop */
2802c8bbce1eSdrh   u16 saved_nSkip;                /* Original value of pNew->nSkip */
28034efc9298Sdrh   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
2804bf539c4dSdrh   LogEst saved_nOut;              /* Original value of pNew->nOut */
28055346e95dSdrh   int rc = SQLITE_OK;             /* Return code */
2806d8b77e20Sdrh   LogEst rSize;                   /* Number of rows in the table */
2807bf539c4dSdrh   LogEst rLogSize;                /* Logarithm of table size */
2808c7f0d229Sdrh   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
28091c8148ffSdrh 
28101c8148ffSdrh   pNew = pBuilder->pNew;
2811fad3039cSmistachkin   if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
2812b035b87eSdrh   WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d, rRun=%d\n",
2813b592d47aSdrh                      pProbe->pTable->zName,pProbe->zName,
2814b035b87eSdrh                      pNew->u.btree.nEq, pNew->nSkip, pNew->rRun));
28151c8148ffSdrh 
28165346e95dSdrh   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
281743fe25fcSdrh   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
281843fe25fcSdrh   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
281943fe25fcSdrh     opMask = WO_LT|WO_LE;
28201c8148ffSdrh   }else{
282171c57db0Sdan     assert( pNew->u.btree.nBtm==0 );
2822e8d0c61fSdrh     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
28231c8148ffSdrh   }
2824ef866376Sdrh   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
28251c8148ffSdrh 
282639129ce8Sdan   assert( pNew->u.btree.nEq<pProbe->nColumn );
2827756748eaSdrh   assert( pNew->u.btree.nEq<pProbe->nKeyCol
2828756748eaSdrh        || pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY );
282939129ce8Sdan 
28304efc9298Sdrh   saved_nEq = pNew->u.btree.nEq;
283171c57db0Sdan   saved_nBtm = pNew->u.btree.nBtm;
283271c57db0Sdan   saved_nTop = pNew->u.btree.nTop;
2833c8bbce1eSdrh   saved_nSkip = pNew->nSkip;
28344efc9298Sdrh   saved_nLTerm = pNew->nLTerm;
28354efc9298Sdrh   saved_wsFlags = pNew->wsFlags;
28364efc9298Sdrh   saved_prereq = pNew->prereq;
28374efc9298Sdrh   saved_nOut = pNew->nOut;
2838bb52308fSdrh   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
2839bb52308fSdrh                         opMask, pProbe);
2840b8a8e8a5Sdrh   pNew->rSetup = 0;
2841d8b77e20Sdrh   rSize = pProbe->aiRowLogEst[0];
2842d8b77e20Sdrh   rLogSize = estLog(rSize);
28435346e95dSdrh   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
28448ad1d8baSdan     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
2845aa9933c1Sdan     LogEst rCostIdx;
28468ad1d8baSdan     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
2847b8a8e8a5Sdrh     int nIn = 0;
2848175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
28497a419235Sdan     int nRecValid = pBuilder->nRecValid;
2850b5246e51Sdrh #endif
28518ad1d8baSdan     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
2852bb52308fSdrh      && indexColumnNotNull(pProbe, saved_nEq)
28538bff07a5Sdan     ){
28548bff07a5Sdan       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
28558bff07a5Sdan     }
28567a419235Sdan     if( pTerm->prereqRight & pNew->maskSelf ) continue;
28577a419235Sdan 
2858a40da62dSdrh     /* Do not allow the upper bound of a LIKE optimization range constraint
2859a40da62dSdrh     ** to mix with a lower range bound from some other source */
2860a40da62dSdrh     if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
2861a40da62dSdrh 
2862faaacd3fSdrh     if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
2863faaacd3fSdrh      && !constraintCompatibleWithOuterJoin(pTerm,pSrc)
28645996a779Sdrh     ){
28655996a779Sdrh       continue;
28665996a779Sdrh     }
2867a3928dd7Sdrh     if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
286889efac94Sdrh       pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
2869a3928dd7Sdrh     }else{
287089efac94Sdrh       pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
2871a3928dd7Sdrh     }
28724efc9298Sdrh     pNew->wsFlags = saved_wsFlags;
28734efc9298Sdrh     pNew->u.btree.nEq = saved_nEq;
287471c57db0Sdan     pNew->u.btree.nBtm = saved_nBtm;
287571c57db0Sdan     pNew->u.btree.nTop = saved_nTop;
28764efc9298Sdrh     pNew->nLTerm = saved_nLTerm;
287774879e13Sdrh     if( pNew->nLTerm>=pNew->nLSlot
287874879e13Sdrh      && whereLoopResize(db, pNew, pNew->nLTerm+1)
287974879e13Sdrh     ){
288074879e13Sdrh        break; /* OOM while trying to enlarge the pNew->aLTerm array */
288174879e13Sdrh     }
28824efc9298Sdrh     pNew->aLTerm[pNew->nLTerm++] = pTerm;
28834efc9298Sdrh     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
28848ad1d8baSdan 
28858ad1d8baSdan     assert( nInMul==0
28868ad1d8baSdan         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
28878ad1d8baSdan         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
28888ad1d8baSdan         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
28898ad1d8baSdan     );
28908ad1d8baSdan 
28918ad1d8baSdan     if( eOp & WO_IN ){
289243fe25fcSdrh       Expr *pExpr = pTerm->pExpr;
2893a4eeccdfSdrh       if( ExprUseXSelect(pExpr) ){
2894e1e2e9acSdrh         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
28953d1fb1ddSdan         int i;
2896bf539c4dSdrh         nIn = 46;  assert( 46==sqlite3LogEst(25) );
28973d1fb1ddSdan 
28983d1fb1ddSdan         /* The expression may actually be of the form (x, y) IN (SELECT...).
28993d1fb1ddSdan         ** In this case there is a separate term for each of (x) and (y).
29003d1fb1ddSdan         ** However, the nIn multiplier should only be applied once, not once
29013d1fb1ddSdan         ** for each such term. The following loop checks that pTerm is the
29023d1fb1ddSdan         ** first such term in use, and sets nIn back to 0 if it is not. */
29033d1fb1ddSdan         for(i=0; i<pNew->nLTerm-1; i++){
29049a2e5169Sdrh           if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
29053d1fb1ddSdan         }
290643fe25fcSdrh       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
290743fe25fcSdrh         /* "x IN (value, value, ...)" */
2908bf539c4dSdrh         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
29093d1fb1ddSdan       }
29107d14ffe4Sdrh       if( pProbe->hasStat1 && rLogSize>=10 ){
2911b034a241Sdrh         LogEst M, logK, x;
2912da4c409aSdrh         /* Let:
2913da4c409aSdrh         **   N = the total number of rows in the table
29146d6decb8Sdrh         **   K = the number of entries on the RHS of the IN operator
2915da4c409aSdrh         **   M = the number of rows in the table that match terms to the
2916da4c409aSdrh         **       to the left in the same index.  If the IN operator is on
2917da4c409aSdrh         **       the left-most index column, M==N.
2918da4c409aSdrh         **
2919da4c409aSdrh         ** Given the definitions above, it is better to omit the IN operator
2920da4c409aSdrh         ** from the index lookup and instead do a scan of the M elements,
2921da4c409aSdrh         ** testing each scanned row against the IN operator separately, if:
2922da4c409aSdrh         **
2923da4c409aSdrh         **        M*log(K) < K*log(N)
2924da4c409aSdrh         **
2925da4c409aSdrh         ** Our estimates for M, K, and N might be inaccurate, so we build in
2926da4c409aSdrh         ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
2927da4c409aSdrh         ** with the index, as using an index has better worst-case behavior.
29286d6decb8Sdrh         ** If we do not have real sqlite_stat1 data, always prefer to use
29297d14ffe4Sdrh         ** the index.  Do not bother with this optimization on very small
29307d14ffe4Sdrh         ** tables (less than 2 rows) as it is pointless in that case.
2931da4c409aSdrh         */
29326d6decb8Sdrh         M = pProbe->aiRowLogEst[saved_nEq];
29336d6decb8Sdrh         logK = estLog(nIn);
2934b034a241Sdrh         /* TUNING      v-----  10 to bias toward indexed IN */
2935b034a241Sdrh         x = M + logK + 10 - (nIn + rLogSize);
2936b034a241Sdrh         if( x>=0 ){
2937da4c409aSdrh           WHERETRACE(0x40,
2938b034a241Sdrh             ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d) "
2939b034a241Sdrh              "prefers indexed lookup\n",
2940b034a241Sdrh              saved_nEq, M, logK, nIn, rLogSize, x));
29413074faabSdrh         }else if( nInMul<2 && OptimizationEnabled(db, SQLITE_SeekScan) ){
2942b034a241Sdrh           WHERETRACE(0x40,
2943b034a241Sdrh             ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
2944b034a241Sdrh              " nInMul=%d) prefers skip-scan\n",
2945b034a241Sdrh              saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
294668cf0aceSdrh           pNew->wsFlags |= WHERE_IN_SEEKSCAN;
2947da4c409aSdrh         }else{
2948da4c409aSdrh           WHERETRACE(0x40,
2949b034a241Sdrh             ("IN operator (N=%d M=%d logK=%d nIn=%d rLogSize=%d x=%d"
2950b034a241Sdrh              " nInMul=%d) prefers normal scan\n",
2951b034a241Sdrh              saved_nEq, M, logK, nIn, rLogSize, x, nInMul));
2952b034a241Sdrh           continue;
2953da4c409aSdrh         }
29546d6decb8Sdrh       }
2955da4c409aSdrh       pNew->wsFlags |= WHERE_COLUMN_IN;
2956e8d0c61fSdrh     }else if( eOp & (WO_EQ|WO_IS) ){
2957bb52308fSdrh       int iCol = pProbe->aiColumn[saved_nEq];
295843fe25fcSdrh       pNew->wsFlags |= WHERE_COLUMN_EQ;
2959bb52308fSdrh       assert( saved_nEq==pNew->u.btree.nEq );
29604b92f98cSdrh       if( iCol==XN_ROWID
296175dbf68bSdan        || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
29624b92f98cSdrh       ){
29634ea48144Sdan         if( iCol==XN_ROWID || pProbe->uniqNotNull
29648433e716Sdan          || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
29658433e716Sdan         ){
29667699d1c4Sdrh           pNew->wsFlags |= WHERE_ONEROW;
29678433e716Sdan         }else{
29688433e716Sdan           pNew->wsFlags |= WHERE_UNQ_WANTED;
296921f7ff7dSdrh         }
2970e39a732cSdrh       }
297167656ac7Sdrh       if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;
29722dd3cdcfSdan     }else if( eOp & WO_ISNULL ){
29732dd3cdcfSdan       pNew->wsFlags |= WHERE_COLUMN_NULL;
29744efa360fSdrh     }else{
29754efa360fSdrh       int nVecLen = whereRangeVectorLen(
29764efa360fSdrh           pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
29774efa360fSdrh       );
29784efa360fSdrh       if( eOp & (WO_GT|WO_GE) ){
29798ad1d8baSdan         testcase( eOp & WO_GT );
29808ad1d8baSdan         testcase( eOp & WO_GE );
298143fe25fcSdrh         pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
29824efa360fSdrh         pNew->u.btree.nBtm = nVecLen;
29836f2bfad2Sdrh         pBtm = pTerm;
29846f2bfad2Sdrh         pTop = 0;
2985a40da62dSdrh         if( pTerm->wtFlags & TERM_LIKEOPT ){
29869a60e716Smistachkin           /* Range constraints that come from the LIKE optimization are
298780314629Sdrh           ** always used in pairs. */
2988a40da62dSdrh           pTop = &pTerm[1];
2989a40da62dSdrh           assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
2990a40da62dSdrh           assert( pTop->wtFlags & TERM_LIKEOPT );
2991a40da62dSdrh           assert( pTop->eOperator==WO_LT );
2992a40da62dSdrh           if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
2993a40da62dSdrh           pNew->aLTerm[pNew->nLTerm++] = pTop;
2994a40da62dSdrh           pNew->wsFlags |= WHERE_TOP_LIMIT;
299571c57db0Sdan           pNew->u.btree.nTop = 1;
2996a40da62dSdrh         }
29972dd3cdcfSdan       }else{
29988ad1d8baSdan         assert( eOp & (WO_LT|WO_LE) );
29998ad1d8baSdan         testcase( eOp & WO_LT );
30008ad1d8baSdan         testcase( eOp & WO_LE );
300143fe25fcSdrh         pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
30024efa360fSdrh         pNew->u.btree.nTop = nVecLen;
30036f2bfad2Sdrh         pTop = pTerm;
30046f2bfad2Sdrh         pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
30054efc9298Sdrh                        pNew->aLTerm[pNew->nLTerm-2] : 0;
300643fe25fcSdrh       }
30074efa360fSdrh     }
30088ad1d8baSdan 
30098ad1d8baSdan     /* At this point pNew->nOut is set to the number of rows expected to
30108ad1d8baSdan     ** be visited by the index scan before considering term pTerm, or the
30118ad1d8baSdan     ** values of nIn and nInMul. In other words, assuming that all
30128ad1d8baSdan     ** "x IN(...)" terms are replaced with "x = ?". This block updates
30138ad1d8baSdan     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
30148ad1d8baSdan     assert( pNew->nOut==saved_nOut );
30156f2bfad2Sdrh     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3016175b8f06Sdrh       /* Adjust nOut using stat4 data. Or, if there is no stat4
3017aa9933c1Sdan       ** data, using some other estimate.  */
3018186ad8ccSdrh       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
30198ad1d8baSdan     }else{
30208ad1d8baSdan       int nEq = ++pNew->u.btree.nEq;
3021e8d0c61fSdrh       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
30228ad1d8baSdan 
30238ad1d8baSdan       assert( pNew->nOut==saved_nOut );
3024bb52308fSdrh       if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
30258ad1d8baSdan         assert( (eOp & WO_IN) || nIn==0 );
3026c5f246ebSdrh         testcase( eOp & WO_IN );
30278ad1d8baSdan         pNew->nOut += pTerm->truthProb;
30288ad1d8baSdan         pNew->nOut -= nIn;
30298ad1d8baSdan       }else{
3030175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
30318ad1d8baSdan         tRowcnt nOut = 0;
30328ad169abSdan         if( nInMul==0
30338ad169abSdan          && pProbe->nSample
30349c32c914Sdrh          && ALWAYS(pNew->u.btree.nEq<=pProbe->nSampleCol)
3035a4eeccdfSdrh          && ((eOp & WO_IN)==0 || ExprUseXList(pTerm->pExpr))
30365eae1d1bSdrh          && OptimizationEnabled(db, SQLITE_Stat4)
30378ad169abSdan         ){
30387a419235Sdan           Expr *pExpr = pTerm->pExpr;
3039e8d0c61fSdrh           if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
3040e8d0c61fSdrh             testcase( eOp & WO_EQ );
3041e8d0c61fSdrh             testcase( eOp & WO_IS );
30428ad1d8baSdan             testcase( eOp & WO_ISNULL );
30437a419235Sdan             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
30448ad1d8baSdan           }else{
30457a419235Sdan             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
30466f2bfad2Sdrh           }
30478ad1d8baSdan           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
30488ad1d8baSdan           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
30496cb8d76cSdan           if( nOut ){
30504f991890Sdrh             pNew->nOut = sqlite3LogEst(nOut);
3051cea1951eSdrh             if( nEq==1
3052f06cdde2Sdrh              /* TUNING: Mark terms as "low selectivity" if they seem likely
3053f06cdde2Sdrh              ** to be true for half or more of the rows in the table.
3054f06cdde2Sdrh              ** See tag-202002240-1 */
3055f06cdde2Sdrh              && pNew->nOut+10 > pProbe->aiRowLogEst[0]
3056cea1951eSdrh             ){
305789efac94Sdrh #if WHERETRACE_ENABLED /* 0x01 */
305889efac94Sdrh               if( sqlite3WhereTrace & 0x01 ){
3059f06cdde2Sdrh                 sqlite3DebugPrintf(
3060f06cdde2Sdrh                    "STAT4 determines term has low selectivity:\n");
306189efac94Sdrh                 sqlite3WhereTermPrint(pTerm, 999);
306289efac94Sdrh               }
306389efac94Sdrh #endif
3064f06cdde2Sdrh               pTerm->wtFlags |= TERM_HIGHTRUTH;
306589efac94Sdrh               if( pTerm->wtFlags & TERM_HEURTRUTH ){
3066f06cdde2Sdrh                 /* If the term has previously been used with an assumption of
3067f06cdde2Sdrh                 ** higher selectivity, then set the flag to rerun the
3068f06cdde2Sdrh                 ** loop computations. */
306989efac94Sdrh                 pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
307089efac94Sdrh               }
307189efac94Sdrh             }
30724f991890Sdrh             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
30738ad1d8baSdan             pNew->nOut -= nIn;
30746cb8d76cSdan           }
30756f2bfad2Sdrh         }
30768ad1d8baSdan         if( nOut==0 )
30776f2bfad2Sdrh #endif
30788ad1d8baSdan         {
30798ad1d8baSdan           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
30808ad1d8baSdan           if( eOp & WO_ISNULL ){
30818ad1d8baSdan             /* TUNING: If there is no likelihood() value, assume that a
30828ad1d8baSdan             ** "col IS NULL" expression matches twice as many rows
30838ad1d8baSdan             ** as (col=?). */
30848ad1d8baSdan             pNew->nOut += 10;
30858ad1d8baSdan           }
30868ad1d8baSdan         }
30878ad1d8baSdan       }
30888ad1d8baSdan     }
30898ad1d8baSdan 
3090aa9933c1Sdan     /* Set rCostIdx to the cost of visiting selected rows in index. Add
3091aa9933c1Sdan     ** it to pNew->rRun, which is currently set to the cost of the index
3092aa9933c1Sdan     ** seek only. Then, if this is a non-covering index, add the cost of
3093aa9933c1Sdan     ** visiting the rows in the main table.  */
3094725dd724Sdrh     assert( pSrc->pTab->szTabRow>0 );
3095aa9933c1Sdan     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
30968ad1d8baSdan     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
3097e217efc8Sdrh     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
3098aa9933c1Sdan       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
3099eb04de32Sdrh     }
3100dbd9486dSdrh     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
3101aa9933c1Sdan 
31028ad1d8baSdan     nOutUnadjusted = pNew->nOut;
31038ad1d8baSdan     pNew->rRun += nInMul + nIn;
31048ad1d8baSdan     pNew->nOut += nInMul + nIn;
3105d8b77e20Sdrh     whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
3106cf8fa7a6Sdrh     rc = whereLoopInsert(pBuilder, pNew);
3107440e6ff3Sdan 
3108440e6ff3Sdan     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
3109440e6ff3Sdan       pNew->nOut = saved_nOut;
3110440e6ff3Sdan     }else{
31118ad1d8baSdan       pNew->nOut = nOutUnadjusted;
3112440e6ff3Sdan     }
31138ad1d8baSdan 
31145346e95dSdrh     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
311539129ce8Sdan      && pNew->u.btree.nEq<pProbe->nColumn
3116756748eaSdrh      && (pNew->u.btree.nEq<pProbe->nKeyCol ||
3117756748eaSdrh            pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)
31185346e95dSdrh     ){
3119b8a8e8a5Sdrh       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
3120f1645f08Sdrh     }
3121ad45ed74Sdan     pNew->nOut = saved_nOut;
3122175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
31237a419235Sdan     pBuilder->nRecValid = nRecValid;
31247a419235Sdan #endif
3125f1645f08Sdrh   }
31264efc9298Sdrh   pNew->prereq = saved_prereq;
31274efc9298Sdrh   pNew->u.btree.nEq = saved_nEq;
312871c57db0Sdan   pNew->u.btree.nBtm = saved_nBtm;
312971c57db0Sdan   pNew->u.btree.nTop = saved_nTop;
3130c8bbce1eSdrh   pNew->nSkip = saved_nSkip;
31314efc9298Sdrh   pNew->wsFlags = saved_wsFlags;
31324efc9298Sdrh   pNew->nOut = saved_nOut;
31334efc9298Sdrh   pNew->nLTerm = saved_nLTerm;
3134c8bbce1eSdrh 
3135c8bbce1eSdrh   /* Consider using a skip-scan if there are no WHERE clause constraints
3136c8bbce1eSdrh   ** available for the left-most terms of the index, and if the average
3137c8bbce1eSdrh   ** number of repeats in the left-most terms is at least 18.
3138c8bbce1eSdrh   **
3139c8bbce1eSdrh   ** The magic number 18 is selected on the basis that scanning 17 rows
3140c8bbce1eSdrh   ** is almost always quicker than an index seek (even though if the index
3141c8bbce1eSdrh   ** contains fewer than 2^17 rows we assume otherwise in other parts of
3142c8bbce1eSdrh   ** the code). And, even if it is not, it should not be too much slower.
3143c8bbce1eSdrh   ** On the other hand, the extra seeks could end up being significantly
3144c8bbce1eSdrh   ** more expensive.  */
3145c8bbce1eSdrh   assert( 42==sqlite3LogEst(18) );
3146c8bbce1eSdrh   if( saved_nEq==saved_nSkip
3147c8bbce1eSdrh    && saved_nEq+1<pProbe->nKeyCol
3148b592d47aSdrh    && saved_nEq==pNew->nLTerm
3149f9df2fbdSdrh    && pProbe->noSkipScan==0
3150ab7fdca2Sdrh    && pProbe->hasStat1!=0
3151e8825519Sdan    && OptimizationEnabled(db, SQLITE_SkipScan)
3152c8bbce1eSdrh    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
3153c8bbce1eSdrh    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
3154c8bbce1eSdrh   ){
3155c8bbce1eSdrh     LogEst nIter;
3156c8bbce1eSdrh     pNew->u.btree.nEq++;
3157c8bbce1eSdrh     pNew->nSkip++;
3158c8bbce1eSdrh     pNew->aLTerm[pNew->nLTerm++] = 0;
3159c8bbce1eSdrh     pNew->wsFlags |= WHERE_SKIPSCAN;
3160c8bbce1eSdrh     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
3161c8bbce1eSdrh     pNew->nOut -= nIter;
3162c8bbce1eSdrh     /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
3163c8bbce1eSdrh     ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
3164c8bbce1eSdrh     nIter += 5;
3165c8bbce1eSdrh     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
3166c8bbce1eSdrh     pNew->nOut = saved_nOut;
3167c8bbce1eSdrh     pNew->u.btree.nEq = saved_nEq;
3168c8bbce1eSdrh     pNew->nSkip = saved_nSkip;
3169c8bbce1eSdrh     pNew->wsFlags = saved_wsFlags;
3170c8bbce1eSdrh   }
3171c8bbce1eSdrh 
31720f1631dbSdrh   WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
31730f1631dbSdrh                       pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
31745346e95dSdrh   return rc;
31751c8148ffSdrh }
31761c8148ffSdrh 
31771c8148ffSdrh /*
317823f98daaSdrh ** Return True if it is possible that pIndex might be useful in
317923f98daaSdrh ** implementing the ORDER BY clause in pBuilder.
318023f98daaSdrh **
318123f98daaSdrh ** Return False if pBuilder does not contain an ORDER BY clause or
318223f98daaSdrh ** if there is no way for pIndex to be useful in implementing that
318323f98daaSdrh ** ORDER BY clause.
318423f98daaSdrh */
indexMightHelpWithOrderBy(WhereLoopBuilder * pBuilder,Index * pIndex,int iCursor)318523f98daaSdrh static int indexMightHelpWithOrderBy(
318623f98daaSdrh   WhereLoopBuilder *pBuilder,
318723f98daaSdrh   Index *pIndex,
318823f98daaSdrh   int iCursor
318923f98daaSdrh ){
319023f98daaSdrh   ExprList *pOB;
3191dae26fe5Sdrh   ExprList *aColExpr;
31926d38147cSdrh   int ii, jj;
319323f98daaSdrh 
319453cfbe92Sdrh   if( pIndex->bUnordered ) return 0;
319570d18344Sdrh   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
319623f98daaSdrh   for(ii=0; ii<pOB->nExpr; ii++){
31970d950af3Sdrh     Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
3198235667a8Sdrh     if( NEVER(pExpr==0) ) continue;
3199dae26fe5Sdrh     if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
3200137fd4fdSdrh       if( pExpr->iColumn<0 ) return 1;
3201bbbdc83bSdrh       for(jj=0; jj<pIndex->nKeyCol; jj++){
32026d38147cSdrh         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
32036d38147cSdrh       }
3204dae26fe5Sdrh     }else if( (aColExpr = pIndex->aColExpr)!=0 ){
3205dae26fe5Sdrh       for(jj=0; jj<pIndex->nKeyCol; jj++){
32064b92f98cSdrh         if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
3207db8e68b4Sdrh         if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
3208dae26fe5Sdrh           return 1;
3209dae26fe5Sdrh         }
3210dae26fe5Sdrh       }
321123f98daaSdrh     }
321223f98daaSdrh   }
321323f98daaSdrh   return 0;
321423f98daaSdrh }
321523f98daaSdrh 
32164bd5f73fSdrh /* Check to see if a partial index with pPartIndexWhere can be used
32174bd5f73fSdrh ** in the current query.  Return true if it can be and false if not.
32184bd5f73fSdrh */
whereUsablePartialIndex(int iTab,u8 jointype,WhereClause * pWC,Expr * pWhere)3219ca7a26b5Sdrh static int whereUsablePartialIndex(
3220ca7a26b5Sdrh   int iTab,             /* The table for which we want an index */
322164481772Sdrh   u8 jointype,          /* The JT_* flags on the join */
3222ca7a26b5Sdrh   WhereClause *pWC,     /* The WHERE clause of the query */
3223ca7a26b5Sdrh   Expr *pWhere          /* The WHERE clause from the partial index */
3224ca7a26b5Sdrh ){
32254bd5f73fSdrh   int i;
32264bd5f73fSdrh   WhereTerm *pTerm;
3227093dd41eSdrh   Parse *pParse;
3228093dd41eSdrh 
3229093dd41eSdrh   if( jointype & JT_LTORJ ) return 0;
3230093dd41eSdrh   pParse = pWC->pWInfo->pParse;
3231cf599b6aSdrh   while( pWhere->op==TK_AND ){
323264481772Sdrh     if( !whereUsablePartialIndex(iTab,jointype,pWC,pWhere->pLeft) ) return 0;
3233cf599b6aSdrh     pWhere = pWhere->pRight;
3234cf599b6aSdrh   }
32353e380a44Sdrh   if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
32364bd5f73fSdrh   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
3237c7d12f4aSdrh     Expr *pExpr;
3238c7d12f4aSdrh     pExpr = pTerm->pExpr;
323967a99dbeSdrh     if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab)
324064481772Sdrh      && ((jointype & JT_OUTER)==0 || ExprHasProperty(pExpr, EP_OuterON))
32413e380a44Sdrh      && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
3242d65b7e36Sdrh      && (pTerm->wtFlags & TERM_VNULL)==0
3243077f06edSdrh     ){
3244077f06edSdrh       return 1;
3245077f06edSdrh     }
32464bd5f73fSdrh   }
32474bd5f73fSdrh   return 0;
32484bd5f73fSdrh }
324992a121f4Sdrh 
325092a121f4Sdrh /*
325154cc766bSdrh ** Structure passed to the whereIsCoveringIndex Walker callback.
325254cc766bSdrh */
325354cc766bSdrh struct CoveringIndexCheck {
325454cc766bSdrh   Index *pIdx;       /* The index */
325554cc766bSdrh   int iTabCur;       /* Cursor number for the corresponding table */
325654cc766bSdrh };
325754cc766bSdrh 
325854cc766bSdrh /*
325954cc766bSdrh ** Information passed in is pWalk->u.pCovIdxCk.  Call is pCk.
326054cc766bSdrh **
326154cc766bSdrh ** If the Expr node references the table with cursor pCk->iTabCur, then
326254cc766bSdrh ** make sure that column is covered by the index pCk->pIdx.  We know that
326354cc766bSdrh ** all columns less than 63 (really BMS-1) are covered, so we don't need
326454cc766bSdrh ** to check them.  But we do need to check any column at 63 or greater.
326554cc766bSdrh **
326654cc766bSdrh ** If the index does not cover the column, then set pWalk->eCode to
326754cc766bSdrh ** non-zero and return WRC_Abort to stop the search.
326854cc766bSdrh **
326954cc766bSdrh ** If this node does not disprove that the index can be a covering index,
327054cc766bSdrh ** then just return WRC_Continue, to continue the search.
327154cc766bSdrh */
whereIsCoveringIndexWalkCallback(Walker * pWalk,Expr * pExpr)327254cc766bSdrh static int whereIsCoveringIndexWalkCallback(Walker *pWalk, Expr *pExpr){
327354cc766bSdrh   int i;                  /* Loop counter */
327454cc766bSdrh   const Index *pIdx;      /* The index of interest */
327554cc766bSdrh   const i16 *aiColumn;    /* Columns contained in the index */
327654cc766bSdrh   u16 nColumn;            /* Number of columns in the index */
3277*7d913e9aSdrh   if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_AGG_COLUMN ) return WRC_Continue;
327854cc766bSdrh   if( pExpr->iColumn<(BMS-1) ) return WRC_Continue;
327954cc766bSdrh   if( pExpr->iTable!=pWalk->u.pCovIdxCk->iTabCur ) return WRC_Continue;
328054cc766bSdrh   pIdx = pWalk->u.pCovIdxCk->pIdx;
328154cc766bSdrh   aiColumn = pIdx->aiColumn;
328254cc766bSdrh   nColumn = pIdx->nColumn;
328354cc766bSdrh   for(i=0; i<nColumn; i++){
328454cc766bSdrh     if( aiColumn[i]==pExpr->iColumn ) return WRC_Continue;
328554cc766bSdrh   }
328654cc766bSdrh   pWalk->eCode = 1;
328754cc766bSdrh   return WRC_Abort;
328854cc766bSdrh }
328954cc766bSdrh 
329054cc766bSdrh 
329154cc766bSdrh /*
329254cc766bSdrh ** pIdx is an index that covers all of the low-number columns used by
329354cc766bSdrh ** pWInfo->pSelect (columns from 0 through 62).  But there are columns
329454cc766bSdrh ** in pWInfo->pSelect beyond 62.  This routine tries to answer the question
329554cc766bSdrh ** of whether pIdx covers *all* columns in the query.
329654cc766bSdrh **
329754cc766bSdrh ** Return 0 if pIdx is a covering index.   Return non-zero if pIdx is
329854cc766bSdrh ** not a covering index or if we are unable to determine if pIdx is a
329954cc766bSdrh ** covering index.
330054cc766bSdrh **
330154cc766bSdrh ** This routine is an optimization.  It is always safe to return non-zero.
330254cc766bSdrh ** But returning zero when non-zero should have been returned can lead to
330354cc766bSdrh ** incorrect bytecode and assertion faults.
330454cc766bSdrh */
whereIsCoveringIndex(WhereInfo * pWInfo,Index * pIdx,int iTabCur)330554cc766bSdrh static SQLITE_NOINLINE u32 whereIsCoveringIndex(
330654cc766bSdrh   WhereInfo *pWInfo,     /* The WHERE clause context */
330754cc766bSdrh   Index *pIdx,           /* Index that is being tested */
330854cc766bSdrh   int iTabCur            /* Cursor for the table being indexed */
330954cc766bSdrh ){
331054cc766bSdrh   int i;
331154cc766bSdrh   struct CoveringIndexCheck ck;
331254cc766bSdrh   Walker w;
331354cc766bSdrh   if( pWInfo->pSelect==0 ){
331454cc766bSdrh     /* We don't have access to the full query, so we cannot check to see
331554cc766bSdrh     ** if pIdx is covering.  Assume it is not. */
331654cc766bSdrh     return 1;
331754cc766bSdrh   }
331854cc766bSdrh   for(i=0; i<pIdx->nColumn; i++){
331954cc766bSdrh     if( pIdx->aiColumn[i]>=BMS-1 ) break;
332054cc766bSdrh   }
332154cc766bSdrh   if( i>=pIdx->nColumn ){
332254cc766bSdrh     /* pIdx does not index any columns greater than 62, but we know from
332354cc766bSdrh     ** colMask that columns greater than 62 are used, so this is not a
332454cc766bSdrh     ** covering index */
332554cc766bSdrh     return 1;
332654cc766bSdrh   }
332754cc766bSdrh   ck.pIdx = pIdx;
332854cc766bSdrh   ck.iTabCur = iTabCur;
332954cc766bSdrh   memset(&w, 0, sizeof(w));
333054cc766bSdrh   w.xExprCallback = whereIsCoveringIndexWalkCallback;
333154cc766bSdrh   w.xSelectCallback = sqlite3SelectWalkNoop;
333254cc766bSdrh   w.u.pCovIdxCk = &ck;
333354cc766bSdrh   w.eCode = 0;
333454cc766bSdrh   sqlite3WalkSelect(&w, pWInfo->pSelect);
333554cc766bSdrh   return w.eCode;
333654cc766bSdrh }
333754cc766bSdrh 
333854cc766bSdrh /*
333951576f47Sdan ** Add all WhereLoop objects for a single table of the join where the table
334071c57db0Sdan ** is identified by pBuilder->pNew->iTab.  That table is guaranteed to be
33410823c89cSdrh ** a b-tree table, not a virtual table.
33428164722cSdan **
33438164722cSdan ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
33448164722cSdan ** are calculated as follows:
33458164722cSdan **
33468164722cSdan ** For a full scan, assuming the table (or index) contains nRow rows:
33478164722cSdan **
33488164722cSdan **     cost = nRow * 3.0                    // full-table scan
33498164722cSdan **     cost = nRow * K                      // scan of covering index
33508164722cSdan **     cost = nRow * (K+3.0)                // scan of non-covering index
33518164722cSdan **
33528164722cSdan ** where K is a value between 1.1 and 3.0 set based on the relative
33538164722cSdan ** estimated average size of the index and table records.
33548164722cSdan **
33558164722cSdan ** For an index scan, where nVisit is the number of index rows visited
33568164722cSdan ** by the scan, and nSeek is the number of seek operations required on
33578164722cSdan ** the index b-tree:
33588164722cSdan **
33598164722cSdan **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
33608164722cSdan **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
33618164722cSdan **
33628164722cSdan ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
33638164722cSdan ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
33648164722cSdan ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
336583a305f2Sdrh **
336683a305f2Sdrh ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
336783a305f2Sdrh ** of uncertainty.  For this reason, scoring is designed to pick plans that
336883a305f2Sdrh ** "do the least harm" if the estimates are inaccurate.  For example, a
336983a305f2Sdrh ** log(nRow) factor is omitted from a non-covering index scan in order to
337083a305f2Sdrh ** bias the scoring in favor of using an index, since the worst-case
337183a305f2Sdrh ** performance of using an index is far better than the worst-case performance
337283a305f2Sdrh ** of a full table scan.
3373f1b5f5b8Sdrh */
whereLoopAddBtree(WhereLoopBuilder * pBuilder,Bitmask mPrereq)33745346e95dSdrh static int whereLoopAddBtree(
33751c8148ffSdrh   WhereLoopBuilder *pBuilder, /* WHERE clause information */
3376599d5764Sdrh   Bitmask mPrereq             /* Extra prerequesites for using this table */
3377f1b5f5b8Sdrh ){
337870d18344Sdrh   WhereInfo *pWInfo;          /* WHERE analysis context */
33791c8148ffSdrh   Index *pProbe;              /* An index we are evaluating */
33801c8148ffSdrh   Index sPk;                  /* A fake index object for the primary key */
3381cfc9df76Sdan   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
3382bbbdc83bSdrh   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
338370d18344Sdrh   SrcList *pTabList;          /* The FROM clause */
33847601294aSdrh   SrcItem *pSrc;              /* The FROM clause btree term to add */
3385f1b5f5b8Sdrh   WhereLoop *pNew;            /* Template WhereLoop object */
33865346e95dSdrh   int rc = SQLITE_OK;         /* Return code */
3387d044d209Sdrh   int iSortIdx = 1;           /* Index number */
338823f98daaSdrh   int b;                      /* A boolean value */
3389bf539c4dSdrh   LogEst rSize;               /* number of rows in the table */
33904bd5f73fSdrh   WhereClause *pWC;           /* The parsed WHERE clause */
33913495d20dSdrh   Table *pTab;                /* Table being queried */
3392f1b5f5b8Sdrh 
33931c8148ffSdrh   pNew = pBuilder->pNew;
339470d18344Sdrh   pWInfo = pBuilder->pWInfo;
339570d18344Sdrh   pTabList = pWInfo->pTabList;
339670d18344Sdrh   pSrc = pTabList->a + pNew->iTab;
33973495d20dSdrh   pTab = pSrc->pTab;
33984bd5f73fSdrh   pWC = pBuilder->pWC;
33990823c89cSdrh   assert( !IsVirtual(pSrc->pTab) );
3400f1b5f5b8Sdrh 
3401271d7c26Sdrh   if( pSrc->fg.isIndexedBy ){
3402dbfbb5a0Sdrh     assert( pSrc->fg.isCte==0 );
34031c8148ffSdrh     /* An INDEXED BY clause specifies a particular index to use */
3404a79e2a2dSdrh     pProbe = pSrc->u2.pIBIndex;
3405ec95c441Sdrh   }else if( !HasRowid(pTab) ){
3406ec95c441Sdrh     pProbe = pTab->pIndex;
34071c8148ffSdrh   }else{
34081c8148ffSdrh     /* There is no INDEXED BY clause.  Create a fake Index object in local
34091c8148ffSdrh     ** variable sPk to represent the rowid primary key index.  Make this
34101c8148ffSdrh     ** fake index the first in a chain of Index objects with all of the real
34111c8148ffSdrh     ** indices to follow */
34121c8148ffSdrh     Index *pFirst;                  /* First of real indices on the table */
34131c8148ffSdrh     memset(&sPk, 0, sizeof(Index));
3414bbbdc83bSdrh     sPk.nKeyCol = 1;
341539129ce8Sdan     sPk.nColumn = 1;
34161c8148ffSdrh     sPk.aiColumn = &aiColumnPk;
3417cfc9df76Sdan     sPk.aiRowLogEst = aiRowEstPk;
34181c8148ffSdrh     sPk.onError = OE_Replace;
34193495d20dSdrh     sPk.pTable = pTab;
3420aa9933c1Sdan     sPk.szIdxRow = pTab->szTabRow;
34215f913ecbSdrh     sPk.idxType = SQLITE_IDXTYPE_IPK;
3422cfc9df76Sdan     aiRowEstPk[0] = pTab->nRowLogEst;
3423cfc9df76Sdan     aiRowEstPk[1] = 0;
34241c8148ffSdrh     pFirst = pSrc->pTab->pIndex;
34258a48b9c0Sdrh     if( pSrc->fg.notIndexed==0 ){
34261c8148ffSdrh       /* The real indices of the table are only considered if the
34271c8148ffSdrh       ** NOT INDEXED qualifier is omitted from the FROM clause */
34281c8148ffSdrh       sPk.pNext = pFirst;
34291c8148ffSdrh     }
34301c8148ffSdrh     pProbe = &sPk;
34311c8148ffSdrh   }
3432cfc9df76Sdan   rSize = pTab->nRowLogEst;
3433eb04de32Sdrh 
3434feb56e0eSdrh #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
3435eb04de32Sdrh   /* Automatic indexes */
3436d092ed43Sdrh   if( !pBuilder->pOrSet      /* Not part of an OR optimization */
3437d345dcf3Sdrh    && (pWInfo->wctrlFlags & (WHERE_RIGHT_JOIN|WHERE_OR_SUBCLAUSE))==0
343870d18344Sdrh    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
3439271d7c26Sdrh    && !pSrc->fg.isIndexedBy  /* Has no INDEXED BY clause */
34408a48b9c0Sdrh    && !pSrc->fg.notIndexed   /* Has no NOT INDEXED clause */
344176226dd2Sdrh    && HasRowid(pTab)         /* Not WITHOUT ROWID table. (FIXME: Why not?) */
34428a48b9c0Sdrh    && !pSrc->fg.isCorrelated /* Not a correlated subquery */
34438a48b9c0Sdrh    && !pSrc->fg.isRecursive  /* Not a recursive common table expression. */
3444529394e5Sdrh    && (pSrc->fg.jointype & JT_RIGHT)==0 /* Not the right tab of a RIGHT JOIN */
3445eb04de32Sdrh   ){
3446eb04de32Sdrh     /* Generate auto-index WhereLoops */
34479045e7d6Sdrh     LogEst rLogSize;         /* Logarithm of the number of rows in the table */
3448eb04de32Sdrh     WhereTerm *pTerm;
3449eb04de32Sdrh     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
34509045e7d6Sdrh     rLogSize = estLog(rSize);
3451eb04de32Sdrh     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
345279a13bfdSdrh       if( pTerm->prereqRight & pNew->maskSelf ) continue;
3453eb04de32Sdrh       if( termCanDriveIndex(pTerm, pSrc, 0) ){
3454eb04de32Sdrh         pNew->u.btree.nEq = 1;
3455c8bbce1eSdrh         pNew->nSkip = 0;
3456ef866376Sdrh         pNew->u.btree.pIndex = 0;
34574efc9298Sdrh         pNew->nLTerm = 1;
34584efc9298Sdrh         pNew->aLTerm[0] = pTerm;
3459e1e2e9acSdrh         /* TUNING: One-time cost for computing the automatic index is
34607e07433fSdrh         ** estimated to be X*N*log2(N) where N is the number of rows in
34617e07433fSdrh         ** the table being indexed and where X is 7 (LogEst=28) for normal
3462492ad131Sdrh         ** tables or 0.5 (LogEst=-10) for views and subqueries.  The value
34637e07433fSdrh         ** of X is smaller for views and subqueries so that the query planner
34647e07433fSdrh         ** will be more aggressive about generating automatic indexes for
34657e07433fSdrh         ** those objects, since there is no opportunity to add schema
34667e07433fSdrh         ** indexes on subqueries and views. */
3467492ad131Sdrh         pNew->rSetup = rLogSize + rSize;
3468f38524d2Sdrh         if( !IsView(pTab) && (pTab->tabFlags & TF_Ephemeral)==0 ){
3469492ad131Sdrh           pNew->rSetup += 28;
3470492ad131Sdrh         }else{
3471492ad131Sdrh           pNew->rSetup -= 10;
34727e07433fSdrh         }
3473dbd9486dSdrh         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
347405d1bad6Sdrh         if( pNew->rSetup<0 ) pNew->rSetup = 0;
3475986b3879Sdrh         /* TUNING: Each index lookup yields 20 rows in the table.  This
3476986b3879Sdrh         ** is more than the usual guess of 10 rows, since we have no way
347760ec914cSpeter.d.reid         ** of knowing how selective the index will ultimately be.  It would
3478986b3879Sdrh         ** not be unreasonable to make this value much larger. */
3479bf539c4dSdrh         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
3480b50596d6Sdrh         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
3481986b3879Sdrh         pNew->wsFlags = WHERE_AUTO_INDEX;
3482599d5764Sdrh         pNew->prereq = mPrereq | pTerm->prereqRight;
3483cf8fa7a6Sdrh         rc = whereLoopInsert(pBuilder, pNew);
3484eb04de32Sdrh       }
3485eb04de32Sdrh     }
3486eb04de32Sdrh   }
3487feb56e0eSdrh #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
34881c8148ffSdrh 
348985e1f46eSdan   /* Loop over all indices. If there was an INDEXED BY clause, then only
349085e1f46eSdan   ** consider index pProbe.  */
349185e1f46eSdan   for(; rc==SQLITE_OK && pProbe;
3492271d7c26Sdrh       pProbe=(pSrc->fg.isIndexedBy ? 0 : pProbe->pNext), iSortIdx++
349385e1f46eSdan   ){
34944bd5f73fSdrh     if( pProbe->pPartIdxWhere!=0
349564481772Sdrh      && !whereUsablePartialIndex(pSrc->iCursor, pSrc->fg.jointype, pWC,
3496ca7a26b5Sdrh                                  pProbe->pPartIdxWhere)
3497ca7a26b5Sdrh     ){
34980829169fSdan       testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
34994bd5f73fSdrh       continue;  /* Partial index inappropriate for this query */
35004bd5f73fSdrh     }
35017e8515d8Sdrh     if( pProbe->bNoQuery ) continue;
35027de2a1faSdan     rSize = pProbe->aiRowLogEst[0];
35035346e95dSdrh     pNew->u.btree.nEq = 0;
350471c57db0Sdan     pNew->u.btree.nBtm = 0;
350571c57db0Sdan     pNew->u.btree.nTop = 0;
3506c8bbce1eSdrh     pNew->nSkip = 0;
35074efc9298Sdrh     pNew->nLTerm = 0;
350823f98daaSdrh     pNew->iSortIdx = 0;
3509b8a8e8a5Sdrh     pNew->rSetup = 0;
3510599d5764Sdrh     pNew->prereq = mPrereq;
351174f91d44Sdrh     pNew->nOut = rSize;
351223f98daaSdrh     pNew->u.btree.pIndex = pProbe;
351323f98daaSdrh     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
3514094afffaSdrh 
351553cfbe92Sdrh     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
351653cfbe92Sdrh     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
35175f913ecbSdrh     if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
351843fe25fcSdrh       /* Integer primary key index */
351943fe25fcSdrh       pNew->wsFlags = WHERE_IPK;
352023f98daaSdrh 
352123f98daaSdrh       /* Full table scan */
3522d044d209Sdrh       pNew->iSortIdx = b ? iSortIdx : 0;
352340386968Sdrh       /* TUNING: Cost of full table scan is 3.0*N.  The 3.0 factor is an
352440386968Sdrh       ** extra cost designed to discourage the use of full table scans,
352540386968Sdrh       ** since index lookups have better worst-case performance if our
352640386968Sdrh       ** stat guesses are wrong.  Reduce the 3.0 penalty slightly
352740386968Sdrh       ** (to 2.75) if we have valid STAT4 information for the table.
352840386968Sdrh       ** At 2.75, a full table scan is preferred over using an index on
352940386968Sdrh       ** a column with just two distinct values where each value has about
353040386968Sdrh       ** an equal number of appearances.  Without STAT4 data, we still want
353140386968Sdrh       ** to use an index in that case, since the constraint might be for
353240386968Sdrh       ** the scarcer of the two values, and in that case an index lookup is
353340386968Sdrh       ** better.
353440386968Sdrh       */
353540386968Sdrh #ifdef SQLITE_ENABLE_STAT4
353640386968Sdrh       pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0);
353740386968Sdrh #else
3538aa9933c1Sdan       pNew->rRun = rSize + 16;
353940386968Sdrh #endif
3540a3fc683cSdrh       if( IsView(pTab) || (pTab->tabFlags & TF_Ephemeral)!=0 ){
3541a3fc683cSdrh         pNew->wsFlags |= WHERE_VIEWSCAN;
3542a3fc683cSdrh       }
3543dbd9486dSdrh       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3544d8b77e20Sdrh       whereLoopOutputAdjust(pWC, pNew, rSize);
354523f98daaSdrh       rc = whereLoopInsert(pBuilder, pNew);
3546cca9f3d2Sdrh       pNew->nOut = rSize;
354723f98daaSdrh       if( rc ) break;
354843fe25fcSdrh     }else{
3549ec95c441Sdrh       Bitmask m;
3550ec95c441Sdrh       if( pProbe->isCovering ){
3551ec95c441Sdrh         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
3552ec95c441Sdrh         m = 0;
3553ec95c441Sdrh       }else{
35541fe3ac73Sdrh         m = pSrc->colUsed & pProbe->colNotIdxed;
355554cc766bSdrh         if( m==TOPBIT ){
355654cc766bSdrh           m = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
355754cc766bSdrh         }
35586fa978daSdrh         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
3559ec95c441Sdrh       }
35601c8148ffSdrh 
356123f98daaSdrh       /* Full scan via index */
356253cfbe92Sdrh       if( b
3563702ba9f2Sdrh        || !HasRowid(pTab)
35648dc570b6Sdrh        || pProbe->pPartIdxWhere!=0
3565094afffaSdrh        || pSrc->fg.isIndexedBy
356653cfbe92Sdrh        || ( m==0
3567e3b7c921Sdrh          && pProbe->bUnordered==0
3568702ba9f2Sdrh          && (pProbe->szIdxRow<pTab->szTabRow)
356970d18344Sdrh          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
3570e3b7c921Sdrh          && sqlite3GlobalConfig.bUseCis
357170d18344Sdrh          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
357253cfbe92Sdrh           )
3573e3b7c921Sdrh       ){
357423f98daaSdrh         pNew->iSortIdx = b ? iSortIdx : 0;
3575aa9933c1Sdan 
3576aa9933c1Sdan         /* The cost of visiting the index rows is N*K, where K is
3577aa9933c1Sdan         ** between 1.1 and 3.0, depending on the relative sizes of the
35782409f8a1Sdrh         ** index and table rows. */
3579aa9933c1Sdan         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
3580aa9933c1Sdan         if( m!=0 ){
35812409f8a1Sdrh           /* If this is a non-covering index scan, add in the cost of
35822409f8a1Sdrh           ** doing table lookups.  The cost will be 3x the number of
35832409f8a1Sdrh           ** lookups.  Take into account WHERE clause terms that can be
35842409f8a1Sdrh           ** satisfied using just the index, and that do not require a
35852409f8a1Sdrh           ** table lookup. */
35862409f8a1Sdrh           LogEst nLookup = rSize + 16;  /* Base cost:  N*3 */
35872409f8a1Sdrh           int ii;
35882409f8a1Sdrh           int iCur = pSrc->iCursor;
358919e76b2aSmistachkin           WhereClause *pWC2 = &pWInfo->sWC;
359019e76b2aSmistachkin           for(ii=0; ii<pWC2->nTerm; ii++){
359119e76b2aSmistachkin             WhereTerm *pTerm = &pWC2->a[ii];
35922409f8a1Sdrh             if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
35932409f8a1Sdrh               break;
35942409f8a1Sdrh             }
35952409f8a1Sdrh             /* pTerm can be evaluated using just the index.  So reduce
35962409f8a1Sdrh             ** the expected number of table lookups accordingly */
35972409f8a1Sdrh             if( pTerm->truthProb<=0 ){
35982409f8a1Sdrh               nLookup += pTerm->truthProb;
35992409f8a1Sdrh             }else{
36002409f8a1Sdrh               nLookup--;
36012409f8a1Sdrh               if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
36022409f8a1Sdrh             }
36032409f8a1Sdrh           }
36042409f8a1Sdrh 
36052409f8a1Sdrh           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
3606e1e2e9acSdrh         }
3607dbd9486dSdrh         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
3608d8b77e20Sdrh         whereLoopOutputAdjust(pWC, pNew, rSize);
360996d55497Sdrh         if( (pSrc->fg.jointype & JT_RIGHT)!=0 && pProbe->aColExpr ){
361096d55497Sdrh           /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN
361196d55497Sdrh           ** because the cursor used to access the index might not be
361296d55497Sdrh           ** positioned to the correct row during the right-join no-match
361396d55497Sdrh           ** loop. */
361496d55497Sdrh         }else{
361523f98daaSdrh           rc = whereLoopInsert(pBuilder, pNew);
361696d55497Sdrh         }
3617cca9f3d2Sdrh         pNew->nOut = rSize;
361823f98daaSdrh         if( rc ) break;
361923f98daaSdrh       }
362023f98daaSdrh     }
36217a419235Sdan 
362289efac94Sdrh     pBuilder->bldFlags1 = 0;
3623b8a8e8a5Sdrh     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
362489efac94Sdrh     if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
3625a3928dd7Sdrh       /* If a non-unique index is used, or if a prefix of the key for
3626a3928dd7Sdrh       ** unique index is used (making the index functionally non-unique)
3627a3928dd7Sdrh       ** then the sqlite_stat1 data becomes important for scoring the
3628a3928dd7Sdrh       ** plan */
3629a3928dd7Sdrh       pTab->tabFlags |= TF_StatsUsed;
3630a3928dd7Sdrh     }
3631175b8f06Sdrh #ifdef SQLITE_ENABLE_STAT4
36327a419235Sdan     sqlite3Stat4ProbeFree(pBuilder->pRec);
36337a419235Sdan     pBuilder->nRecValid = 0;
36347a419235Sdan     pBuilder->pRec = 0;
3635ddc2d6e8Sdan #endif
36361c8148ffSdrh   }
36375346e95dSdrh   return rc;
3638f1b5f5b8Sdrh }
3639f1b5f5b8Sdrh 
36408636e9c5Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
3641115305ffSdan 
3642f1b5f5b8Sdrh /*
3643895bab33Sdrh ** Return true if pTerm is a virtual table LIMIT or OFFSET term.
3644895bab33Sdrh */
isLimitTerm(WhereTerm * pTerm)3645895bab33Sdrh static int isLimitTerm(WhereTerm *pTerm){
36468f2c0b59Sdrh   assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
36478f2c0b59Sdrh   return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
36488f2c0b59Sdrh       && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
3649895bab33Sdrh }
3650895bab33Sdrh 
3651895bab33Sdrh /*
3652115305ffSdan ** Argument pIdxInfo is already populated with all constraints that may
3653115305ffSdan ** be used by the virtual table identified by pBuilder->pNew->iTab. This
3654115305ffSdan ** function marks a subset of those constraints usable, invokes the
3655115305ffSdan ** xBestIndex method and adds the returned plan to pBuilder.
36564f20cd40Sdan **
3657115305ffSdan ** A constraint is marked usable if:
36584f20cd40Sdan **
3659115305ffSdan **   * Argument mUsable indicates that its prerequisites are available, and
36604f20cd40Sdan **
3661115305ffSdan **   * It is not one of the operators specified in the mExclude mask passed
3662115305ffSdan **     as the fourth argument (which in practice is either WO_IN or 0).
36634f20cd40Sdan **
3664599d5764Sdrh ** Argument mPrereq is a mask of tables that must be scanned before the
3665115305ffSdan ** virtual table in question. These are added to the plans prerequisites
3666115305ffSdan ** before it is added to pBuilder.
36674f20cd40Sdan **
3668115305ffSdan ** Output parameter *pbIn is set to true if the plan added to pBuilder
3669115305ffSdan ** uses one or more WO_IN terms, or false otherwise.
3670f1b5f5b8Sdrh */
whereLoopAddVirtualOne(WhereLoopBuilder * pBuilder,Bitmask mPrereq,Bitmask mUsable,u16 mExclude,sqlite3_index_info * pIdxInfo,u16 mNoOmit,int * pbIn,int * pbRetryLimit)3671115305ffSdan static int whereLoopAddVirtualOne(
3672115305ffSdan   WhereLoopBuilder *pBuilder,
3673599d5764Sdrh   Bitmask mPrereq,                /* Mask of tables that must be used. */
36748426e36cSdrh   Bitmask mUsable,                /* Mask of usable tables */
36758426e36cSdrh   u16 mExclude,                   /* Exclude terms using these operators */
3676115305ffSdan   sqlite3_index_info *pIdxInfo,   /* Populated object for xBestIndex */
36776256c1c2Sdan   u16 mNoOmit,                    /* Do not omit these constraints */
3678895bab33Sdrh   int *pbIn,                      /* OUT: True if plan uses an IN(...) op */
3679895bab33Sdrh   int *pbRetryLimit               /* OUT: Retry without LIMIT/OFFSET */
3680f1b5f5b8Sdrh ){
3681115305ffSdan   WhereClause *pWC = pBuilder->pWC;
36820fe7e7d9Sdrh   HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
36835346e95dSdrh   struct sqlite3_index_constraint *pIdxCons;
3684115305ffSdan   struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
3685115305ffSdan   int i;
3686115305ffSdan   int mxTerm;
36875346e95dSdrh   int rc = SQLITE_OK;
3688115305ffSdan   WhereLoop *pNew = pBuilder->pNew;
3689115305ffSdan   Parse *pParse = pBuilder->pWInfo->pParse;
36907601294aSdrh   SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
3691115305ffSdan   int nConstraint = pIdxInfo->nConstraint;
36925346e95dSdrh 
3693599d5764Sdrh   assert( (mUsable & mPrereq)==mPrereq );
3694115305ffSdan   *pbIn = 0;
3695599d5764Sdrh   pNew->prereq = mPrereq;
36965346e95dSdrh 
3697115305ffSdan   /* Set the usable flag on the subset of constraints identified by
3698115305ffSdan   ** arguments mUsable and mExclude. */
36995346e95dSdrh   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
3700115305ffSdan   for(i=0; i<nConstraint; i++, pIdxCons++){
3701115305ffSdan     WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
37025346e95dSdrh     pIdxCons->usable = 0;
3703115305ffSdan     if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
3704115305ffSdan      && (pTerm->eOperator & mExclude)==0
3705895bab33Sdrh      && (pbRetryLimit || !isLimitTerm(pTerm))
3706115305ffSdan     ){
37075346e95dSdrh       pIdxCons->usable = 1;
37085346e95dSdrh     }
37095346e95dSdrh   }
3710115305ffSdan 
3711115305ffSdan   /* Initialize the output fields of the sqlite3_index_info structure */
3712115305ffSdan   memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
3713d1cca3b7Sdrh   assert( pIdxInfo->needToFreeIdxStr==0 );
37145346e95dSdrh   pIdxInfo->idxStr = 0;
37155346e95dSdrh   pIdxInfo->idxNum = 0;
37165346e95dSdrh   pIdxInfo->orderByConsumed = 0;
37178636e9c5Sdrh   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
3718a9f5815bSdan   pIdxInfo->estimatedRows = 25;
3719b3deb4eaSdan   pIdxInfo->idxFlags = 0;
37201acb539fSdan   pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
37210fe7e7d9Sdrh   pHidden->mHandleIn = 0;
3722115305ffSdan 
3723115305ffSdan   /* Invoke the virtual table xBestIndex() method */
3724115305ffSdan   rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
372532dcc847Sdrh   if( rc ){
372632dcc847Sdrh     if( rc==SQLITE_CONSTRAINT ){
372732dcc847Sdrh       /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
372832dcc847Sdrh       ** that the particular combination of parameters provided is unusable.
372932dcc847Sdrh       ** Make no entries in the loop table.
373032dcc847Sdrh       */
3731e4f90b70Sdrh       WHERETRACE(0xffff, ("  ^^^^--- non-viable plan rejected!\n"));
373232dcc847Sdrh       return SQLITE_OK;
373332dcc847Sdrh     }
373432dcc847Sdrh     return rc;
373532dcc847Sdrh   }
3736115305ffSdan 
3737c718f1c8Sdrh   mxTerm = -1;
37384efc9298Sdrh   assert( pNew->nLSlot>=nConstraint );
37398f2c0b59Sdrh   memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
37408f2c0b59Sdrh   memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
3741115305ffSdan   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
37424efc9298Sdrh   for(i=0; i<nConstraint; i++, pIdxCons++){
3743115305ffSdan     int iTerm;
37445346e95dSdrh     if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
3745115305ffSdan       WhereTerm *pTerm;
3746115305ffSdan       int j = pIdxCons->iTermOffset;
37474efc9298Sdrh       if( iTerm>=nConstraint
37485346e95dSdrh        || j<0
37495346e95dSdrh        || j>=pWC->nTerm
37504efc9298Sdrh        || pNew->aLTerm[iTerm]!=0
37516de32e7cSdrh        || pIdxCons->usable==0
37525346e95dSdrh       ){
37536de32e7cSdrh         sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
3754337679beSdrh         testcase( pIdxInfo->needToFreeIdxStr );
3755337679beSdrh         return SQLITE_ERROR;
37565346e95dSdrh       }
37577963b0e8Sdrh       testcase( iTerm==nConstraint-1 );
37587963b0e8Sdrh       testcase( j==0 );
37597963b0e8Sdrh       testcase( j==pWC->nTerm-1 );
37605346e95dSdrh       pTerm = &pWC->a[j];
37615346e95dSdrh       pNew->prereq |= pTerm->prereqRight;
37624efc9298Sdrh       assert( iTerm<pNew->nLSlot );
37634efc9298Sdrh       pNew->aLTerm[iTerm] = pTerm;
37645346e95dSdrh       if( iTerm>mxTerm ) mxTerm = iTerm;
37657963b0e8Sdrh       testcase( iTerm==15 );
37667963b0e8Sdrh       testcase( iTerm==16 );
376739593e4fSdrh       if( pUsage[i].omit ){
376839593e4fSdrh         if( i<16 && ((1<<i)&mNoOmit)==0 ){
3769b6c94725Sdrh           testcase( i!=iTerm );
3770b6c94725Sdrh           pNew->u.vtab.omitMask |= 1<<iTerm;
3771b6c94725Sdrh         }else{
3772b6c94725Sdrh           testcase( i!=iTerm );
3773b6c94725Sdrh         }
37748f2c0b59Sdrh         if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){
37758f2c0b59Sdrh           pNew->u.vtab.bOmitOffset = 1;
37768f2c0b59Sdrh         }
3777b6c94725Sdrh       }
37780fe7e7d9Sdrh       if( SMASKBIT32(i) & pHidden->mHandleIn ){
3779b30298d3Sdrh         pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm);
37800fe7e7d9Sdrh       }else if( (pTerm->eOperator & WO_IN)!=0 ){
37815346e95dSdrh         /* A virtual table that is constrained by an IN clause may not
37825346e95dSdrh         ** consume the ORDER BY clause because (1) the order of IN terms
37835346e95dSdrh         ** is not necessarily related to the order of output terms and
37845346e95dSdrh         ** (2) Multiple outputs from a single IN value will not merge
37855346e95dSdrh         ** together.  */
37865346e95dSdrh         pIdxInfo->orderByConsumed = 0;
3787b3deb4eaSdan         pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
37886de32e7cSdrh         *pbIn = 1; assert( (mExclude & WO_IN)==0 );
37895346e95dSdrh       }
3790895bab33Sdrh 
379151e5d447Sdrh       assert( pbRetryLimit || !isLimitTerm(pTerm) );
3792895bab33Sdrh       if( isLimitTerm(pTerm) && *pbIn ){
3793895bab33Sdrh         /* If there is an IN(...) term handled as an == (separate call to
3794895bab33Sdrh         ** xFilter for each value on the RHS of the IN) and a LIMIT or
3795895bab33Sdrh         ** OFFSET term handled as well, the plan is unusable. Set output
3796895bab33Sdrh         ** variable *pbRetryLimit to true to tell the caller to retry with
3797895bab33Sdrh         ** LIMIT and OFFSET disabled. */
3798895bab33Sdrh         if( pIdxInfo->needToFreeIdxStr ){
3799895bab33Sdrh           sqlite3_free(pIdxInfo->idxStr);
3800895bab33Sdrh           pIdxInfo->idxStr = 0;
3801895bab33Sdrh           pIdxInfo->needToFreeIdxStr = 0;
3802895bab33Sdrh         }
3803895bab33Sdrh         *pbRetryLimit = 1;
3804895bab33Sdrh         return SQLITE_OK;
3805895bab33Sdrh       }
38065346e95dSdrh     }
38075346e95dSdrh   }
3808115305ffSdan 
38094efc9298Sdrh   pNew->nLTerm = mxTerm+1;
3810337679beSdrh   for(i=0; i<=mxTerm; i++){
3811337679beSdrh     if( pNew->aLTerm[i]==0 ){
3812337679beSdrh       /* The non-zero argvIdx values must be contiguous.  Raise an
3813337679beSdrh       ** error if they are not */
3814337679beSdrh       sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
3815337679beSdrh       testcase( pIdxInfo->needToFreeIdxStr );
3816337679beSdrh       return SQLITE_ERROR;
3817337679beSdrh     }
3818337679beSdrh   }
38194efc9298Sdrh   assert( pNew->nLTerm<=pNew->nLSlot );
38205346e95dSdrh   pNew->u.vtab.idxNum = pIdxInfo->idxNum;
38215346e95dSdrh   pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
38225346e95dSdrh   pIdxInfo->needToFreeIdxStr = 0;
38235346e95dSdrh   pNew->u.vtab.idxStr = pIdxInfo->idxStr;
38240401acecSdrh   pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
38250401acecSdrh       pIdxInfo->nOrderBy : 0);
3826b8a8e8a5Sdrh   pNew->rSetup = 0;
3827b50596d6Sdrh   pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
3828a9f5815bSdan   pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
3829076e0f96Sdan 
3830076e0f96Sdan   /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
3831076e0f96Sdan   ** that the scan will visit at most one row. Clear it otherwise. */
3832b3deb4eaSdan   if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
3833076e0f96Sdan     pNew->wsFlags |= WHERE_ONEROW;
3834076e0f96Sdan   }else{
3835076e0f96Sdan     pNew->wsFlags &= ~WHERE_ONEROW;
3836076e0f96Sdan   }
3837bacbbccdSdrh   rc = whereLoopInsert(pBuilder, pNew);
38385346e95dSdrh   if( pNew->u.vtab.needFree ){
38395346e95dSdrh     sqlite3_free(pNew->u.vtab.idxStr);
38405346e95dSdrh     pNew->u.vtab.needFree = 0;
38415346e95dSdrh   }
38423349d9beSdrh   WHERETRACE(0xffff, ("  bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
38433349d9beSdrh                       *pbIn, (sqlite3_uint64)mPrereq,
38443349d9beSdrh                       (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
3845115305ffSdan 
3846bacbbccdSdrh   return rc;
3847115305ffSdan }
3848115305ffSdan 
3849e01b9281Sdan /*
3850b6592f65Sdrh ** Return the collating sequence for a constraint passed into xBestIndex.
3851b6592f65Sdrh **
3852b6592f65Sdrh ** pIdxInfo must be an sqlite3_index_info structure passed into xBestIndex.
3853b6592f65Sdrh ** This routine depends on there being a HiddenIndexInfo structure immediately
3854b6592f65Sdrh ** following the sqlite3_index_info structure.
3855b6592f65Sdrh **
3856b6592f65Sdrh ** Return a pointer to the collation name:
3857b6592f65Sdrh **
3858b6592f65Sdrh **    1. If there is an explicit COLLATE operator on the constaint, return it.
3859b6592f65Sdrh **
3860b6592f65Sdrh **    2. Else, if the column has an alternative collation, return that.
3861b6592f65Sdrh **
3862b6592f65Sdrh **    3. Otherwise, return "BINARY".
3863e01b9281Sdan */
sqlite3_vtab_collation(sqlite3_index_info * pIdxInfo,int iCons)3864efc88d02Sdrh const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
3865efc88d02Sdrh   HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
38660824ccf2Sdan   const char *zRet = 0;
3867efc88d02Sdrh   if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
3868e42e1bc5Sdan     CollSeq *pC = 0;
3869efc88d02Sdrh     int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
3870efc88d02Sdrh     Expr *pX = pHidden->pWC->a[iTerm].pExpr;
3871e42e1bc5Sdan     if( pX->pLeft ){
3872898c527eSdrh       pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
3873e42e1bc5Sdan     }
38747810ab64Sdrh     zRet = (pC ? pC->zName : sqlite3StrBINARY);
38750824ccf2Sdan   }
38760824ccf2Sdan   return zRet;
38770824ccf2Sdan }
38780824ccf2Sdan 
3879f1b5f5b8Sdrh /*
38800fe7e7d9Sdrh ** Return true if constraint iCons is really an IN(...) constraint, or
38810fe7e7d9Sdrh ** false otherwise. If iCons is an IN(...) constraint, set (if bHandle!=0)
38820fe7e7d9Sdrh ** or clear (if bHandle==0) the flag to handle it using an iterator.
38830fe7e7d9Sdrh */
sqlite3_vtab_in(sqlite3_index_info * pIdxInfo,int iCons,int bHandle)38840fe7e7d9Sdrh int sqlite3_vtab_in(sqlite3_index_info *pIdxInfo, int iCons, int bHandle){
38850fe7e7d9Sdrh   HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
38860fe7e7d9Sdrh   u32 m = SMASKBIT32(iCons);
38870fe7e7d9Sdrh   if( m & pHidden->mIn ){
38880fe7e7d9Sdrh     if( bHandle==0 ){
38890fe7e7d9Sdrh       pHidden->mHandleIn &= ~m;
3890b30298d3Sdrh     }else if( bHandle>0 ){
38910fe7e7d9Sdrh       pHidden->mHandleIn |= m;
38920fe7e7d9Sdrh     }
38930fe7e7d9Sdrh     return 1;
38940fe7e7d9Sdrh   }
38950fe7e7d9Sdrh   return 0;
38960fe7e7d9Sdrh }
38970fe7e7d9Sdrh 
38980fe7e7d9Sdrh /*
389982801a5bSdrh ** This interface is callable from within the xBestIndex callback only.
390082801a5bSdrh **
390182801a5bSdrh ** If possible, set (*ppVal) to point to an object containing the value
390282801a5bSdrh ** on the right-hand-side of constraint iCons.
390382801a5bSdrh */
sqlite3_vtab_rhs_value(sqlite3_index_info * pIdxInfo,int iCons,sqlite3_value ** ppVal)390482801a5bSdrh int sqlite3_vtab_rhs_value(
390582801a5bSdrh   sqlite3_index_info *pIdxInfo,   /* Copy of first argument to xBestIndex */
390682801a5bSdrh   int iCons,                      /* Constraint for which RHS is wanted */
390782801a5bSdrh   sqlite3_value **ppVal           /* Write value extracted here */
390882801a5bSdrh ){
390982801a5bSdrh   HiddenIndexInfo *pH = (HiddenIndexInfo*)&pIdxInfo[1];
391082801a5bSdrh   sqlite3_value *pVal = 0;
391182801a5bSdrh   int rc = SQLITE_OK;
391282801a5bSdrh   if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
3913991d1085Sdrh     rc = SQLITE_MISUSE; /* EV: R-30545-25046 */
391482801a5bSdrh   }else{
391582801a5bSdrh     if( pH->aRhs[iCons]==0 ){
391682801a5bSdrh       WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
391782801a5bSdrh       rc = sqlite3ValueFromExpr(
391882801a5bSdrh           pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
391982801a5bSdrh           SQLITE_AFF_BLOB, &pH->aRhs[iCons]
392082801a5bSdrh       );
3921991d1085Sdrh       testcase( rc!=SQLITE_OK );
392282801a5bSdrh     }
392382801a5bSdrh     pVal = pH->aRhs[iCons];
392482801a5bSdrh   }
392582801a5bSdrh   *ppVal = pVal;
3926991d1085Sdrh 
3927a1c8151bSdrh   if( rc==SQLITE_OK && pVal==0 ){  /* IMP: R-19933-32160 */
3928991d1085Sdrh     rc = SQLITE_NOTFOUND;          /* IMP: R-36424-56542 */
3929991d1085Sdrh   }
3930991d1085Sdrh 
393182801a5bSdrh   return rc;
393282801a5bSdrh }
393382801a5bSdrh 
3934ec778d27Sdrh /*
3935ec778d27Sdrh ** Return true if ORDER BY clause may be handled as DISTINCT.
3936ec778d27Sdrh */
sqlite3_vtab_distinct(sqlite3_index_info * pIdxInfo)3937ec778d27Sdrh int sqlite3_vtab_distinct(sqlite3_index_info *pIdxInfo){
3938ec778d27Sdrh   HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
3939d6df8550Sdrh   assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
3940ec778d27Sdrh   return pHidden->eDistinct;
3941ec778d27Sdrh }
3942ec778d27Sdrh 
394346dc631aSdrh #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
394446dc631aSdrh     && !defined(SQLITE_OMIT_VIRTUALTABLE)
394546dc631aSdrh /*
394646dc631aSdrh ** Cause the prepared statement that is associated with a call to
39477d0ae003Sdrh ** xBestIndex to potentiall use all schemas.  If the statement being
39487d0ae003Sdrh ** prepared is read-only, then just start read transactions on all
39497d0ae003Sdrh ** schemas.  But if this is a write operation, start writes on all
39507d0ae003Sdrh ** schemas.
39517d0ae003Sdrh **
395246dc631aSdrh ** This is used by the (built-in) sqlite_dbpage virtual table.
395346dc631aSdrh */
sqlite3VtabUsesAllSchemas(sqlite3_index_info * pIdxInfo)39547d0ae003Sdrh void sqlite3VtabUsesAllSchemas(sqlite3_index_info *pIdxInfo){
395546dc631aSdrh   HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
395646dc631aSdrh   Parse *pParse = pHidden->pParse;
39576a51e70cSdrh   int nDb = pParse->db->nDb;
39586a51e70cSdrh   int i;
39597d0ae003Sdrh   for(i=0; i<nDb; i++){
39607d0ae003Sdrh     sqlite3CodeVerifySchema(pParse, i);
39617d0ae003Sdrh   }
39627d0ae003Sdrh   if( pParse->writeMask ){
39637d0ae003Sdrh     for(i=0; i<nDb; i++){
39647d0ae003Sdrh       sqlite3BeginWriteOperation(pParse, 0, i);
39657d0ae003Sdrh     }
39667d0ae003Sdrh   }
396746dc631aSdrh }
396846dc631aSdrh #endif
396946dc631aSdrh 
397082801a5bSdrh /*
3971f1b5f5b8Sdrh ** Add all WhereLoop objects for a table of the join identified by
3972f1b5f5b8Sdrh ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
3973f1b5f5b8Sdrh **
3974599d5764Sdrh ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
3975599d5764Sdrh ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
3976f1b5f5b8Sdrh ** entries that occur before the virtual table in the FROM clause and are
3977f1b5f5b8Sdrh ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
3978f1b5f5b8Sdrh ** mUnusable mask contains all FROM clause entries that occur after the
3979f1b5f5b8Sdrh ** virtual table and are separated from it by at least one LEFT or
3980f1b5f5b8Sdrh ** CROSS JOIN.
3981f1b5f5b8Sdrh **
3982f1b5f5b8Sdrh ** For example, if the query were:
3983f1b5f5b8Sdrh **
3984f1b5f5b8Sdrh **   ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
3985f1b5f5b8Sdrh **
3986599d5764Sdrh ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
3987f1b5f5b8Sdrh **
3988599d5764Sdrh ** All the tables in mPrereq must be scanned before the current virtual
3989f1b5f5b8Sdrh ** table. So any terms for which all prerequisites are satisfied by
3990599d5764Sdrh ** mPrereq may be specified as "usable" in all calls to xBestIndex.
3991f1b5f5b8Sdrh ** Conversely, all tables in mUnusable must be scanned after the current
3992f1b5f5b8Sdrh ** virtual table, so any terms for which the prerequisites overlap with
3993f1b5f5b8Sdrh ** mUnusable should always be configured as "not-usable" for xBestIndex.
3994f1b5f5b8Sdrh */
whereLoopAddVirtual(WhereLoopBuilder * pBuilder,Bitmask mPrereq,Bitmask mUnusable)3995f1b5f5b8Sdrh static int whereLoopAddVirtual(
3996f1b5f5b8Sdrh   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
3997599d5764Sdrh   Bitmask mPrereq,             /* Tables that must be scanned before this one */
3998f1b5f5b8Sdrh   Bitmask mUnusable            /* Tables that must be scanned after this one */
3999f1b5f5b8Sdrh ){
4000115305ffSdan   int rc = SQLITE_OK;          /* Return code */
4001f1b5f5b8Sdrh   WhereInfo *pWInfo;           /* WHERE analysis context */
4002f1b5f5b8Sdrh   Parse *pParse;               /* The parsing context */
4003f1b5f5b8Sdrh   WhereClause *pWC;            /* The WHERE clause */
40047601294aSdrh   SrcItem *pSrc;               /* The FROM clause term to search */
4005115305ffSdan   sqlite3_index_info *p;       /* Object to pass to xBestIndex() */
4006115305ffSdan   int nConstraint;             /* Number of constraints in p */
4007115305ffSdan   int bIn;                     /* True if plan uses IN(...) operator */
40085346e95dSdrh   WhereLoop *pNew;
4009115305ffSdan   Bitmask mBest;               /* Tables used by best possible plan */
40106256c1c2Sdan   u16 mNoOmit;
4011895bab33Sdrh   int bRetry = 0;              /* True to retry with LIMIT/OFFSET disabled */
40125346e95dSdrh 
4013599d5764Sdrh   assert( (mPrereq & mUnusable)==0 );
40145346e95dSdrh   pWInfo = pBuilder->pWInfo;
40155346e95dSdrh   pParse = pWInfo->pParse;
40165346e95dSdrh   pWC = pBuilder->pWC;
40175346e95dSdrh   pNew = pBuilder->pNew;
40185346e95dSdrh   pSrc = &pWInfo->pTabList->a[pNew->iTab];
4019115305ffSdan   assert( IsVirtual(pSrc->pTab) );
4020ec778d27Sdrh   p = allocateIndexInfo(pWInfo, pWC, mUnusable, pSrc, &mNoOmit);
4021115305ffSdan   if( p==0 ) return SQLITE_NOMEM_BKPT;
40225346e95dSdrh   pNew->rSetup = 0;
40235346e95dSdrh   pNew->wsFlags = WHERE_VIRTUALTABLE;
40245346e95dSdrh   pNew->nLTerm = 0;
40255346e95dSdrh   pNew->u.vtab.needFree = 0;
4026115305ffSdan   nConstraint = p->nConstraint;
4027115305ffSdan   if( whereLoopResize(pParse->db, pNew, nConstraint) ){
402882801a5bSdrh     freeIndexInfo(pParse->db, p);
4029fad3039cSmistachkin     return SQLITE_NOMEM_BKPT;
40305346e95dSdrh   }
40315346e95dSdrh 
4032115305ffSdan   /* First call xBestIndex() with all constraints usable. */
40330f1631dbSdrh   WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
40343349d9beSdrh   WHERETRACE(0x40, ("  VirtualOne: all usable\n"));
4035895bab33Sdrh   rc = whereLoopAddVirtualOne(
4036895bab33Sdrh       pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, &bRetry
4037895bab33Sdrh   );
4038895bab33Sdrh   if( bRetry ){
4039895bab33Sdrh     assert( rc==SQLITE_OK );
4040895bab33Sdrh     rc = whereLoopAddVirtualOne(
4041895bab33Sdrh         pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn, 0
4042895bab33Sdrh     );
4043895bab33Sdrh   }
40445346e95dSdrh 
4045115305ffSdan   /* If the call to xBestIndex() with all terms enabled produced a plan
404635808435Sdan   ** that does not require any source tables (IOW: a plan with mBest==0)
404735808435Sdan   ** and does not use an IN(...) operator, then there is no point in making
404835808435Sdan   ** any further calls to xBestIndex() since they will all return the same
404935808435Sdan   ** result (if the xBestIndex() implementation is sane). */
405035808435Sdan   if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
4051115305ffSdan     int seenZero = 0;             /* True if a plan with no prereqs seen */
4052115305ffSdan     int seenZeroNoIN = 0;         /* Plan with no prereqs and no IN(...) seen */
4053115305ffSdan     Bitmask mPrev = 0;
4054115305ffSdan     Bitmask mBestNoIn = 0;
4055115305ffSdan 
4056115305ffSdan     /* If the plan produced by the earlier call uses an IN(...) term, call
4057115305ffSdan     ** xBestIndex again, this time with IN(...) terms disabled. */
40583349d9beSdrh     if( bIn ){
40593349d9beSdrh       WHERETRACE(0x40, ("  VirtualOne: all usable w/o IN\n"));
40606256c1c2Sdan       rc = whereLoopAddVirtualOne(
4061895bab33Sdrh           pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn, 0);
40626de32e7cSdrh       assert( bIn==0 );
4063599d5764Sdrh       mBestNoIn = pNew->prereq & ~mPrereq;
4064115305ffSdan       if( mBestNoIn==0 ){
4065115305ffSdan         seenZero = 1;
40666de32e7cSdrh         seenZeroNoIN = 1;
40675346e95dSdrh       }
40685346e95dSdrh     }
40695346e95dSdrh 
4070599d5764Sdrh     /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
4071115305ffSdan     ** in the set of terms that apply to the current virtual table.  */
4072115305ffSdan     while( rc==SQLITE_OK ){
4073115305ffSdan       int i;
40748426e36cSdrh       Bitmask mNext = ALLBITS;
4075115305ffSdan       assert( mNext>0 );
4076115305ffSdan       for(i=0; i<nConstraint; i++){
4077115305ffSdan         Bitmask mThis = (
4078599d5764Sdrh             pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
4079115305ffSdan         );
4080115305ffSdan         if( mThis>mPrev && mThis<mNext ) mNext = mThis;
4081115305ffSdan       }
4082115305ffSdan       mPrev = mNext;
40838426e36cSdrh       if( mNext==ALLBITS ) break;
4084115305ffSdan       if( mNext==mBest || mNext==mBestNoIn ) continue;
40853349d9beSdrh       WHERETRACE(0x40, ("  VirtualOne: mPrev=%04llx mNext=%04llx\n",
40863349d9beSdrh                        (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
40876256c1c2Sdan       rc = whereLoopAddVirtualOne(
4088895bab33Sdrh           pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn, 0);
4089599d5764Sdrh       if( pNew->prereq==mPrereq ){
4090115305ffSdan         seenZero = 1;
4091115305ffSdan         if( bIn==0 ) seenZeroNoIN = 1;
4092115305ffSdan       }
4093115305ffSdan     }
4094115305ffSdan 
4095115305ffSdan     /* If the calls to xBestIndex() in the above loop did not find a plan
4096115305ffSdan     ** that requires no source tables at all (i.e. one guaranteed to be
4097115305ffSdan     ** usable), make a call here with all source tables disabled */
4098115305ffSdan     if( rc==SQLITE_OK && seenZero==0 ){
40993349d9beSdrh       WHERETRACE(0x40, ("  VirtualOne: all disabled\n"));
41006256c1c2Sdan       rc = whereLoopAddVirtualOne(
4101895bab33Sdrh           pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn, 0);
4102115305ffSdan       if( bIn==0 ) seenZeroNoIN = 1;
4103115305ffSdan     }
4104115305ffSdan 
4105115305ffSdan     /* If the calls to xBestIndex() have so far failed to find a plan
4106115305ffSdan     ** that requires no source tables at all and does not use an IN(...)
4107115305ffSdan     ** operator, make a final call to obtain one here.  */
4108115305ffSdan     if( rc==SQLITE_OK && seenZeroNoIN==0 ){
41093349d9beSdrh       WHERETRACE(0x40, ("  VirtualOne: all disabled and w/o IN\n"));
41106256c1c2Sdan       rc = whereLoopAddVirtualOne(
4111895bab33Sdrh           pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn, 0);
4112115305ffSdan     }
4113115305ffSdan   }
4114115305ffSdan 
4115115305ffSdan   if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
411682801a5bSdrh   freeIndexInfo(pParse->db, p);
41170f1631dbSdrh   WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
41185346e95dSdrh   return rc;
4119f1b5f5b8Sdrh }
41208636e9c5Sdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */
4121f1b5f5b8Sdrh 
4122f1b5f5b8Sdrh /*
4123cf8fa7a6Sdrh ** Add WhereLoop entries to handle OR terms.  This works for either
4124cf8fa7a6Sdrh ** btrees or virtual tables.
4125cf8fa7a6Sdrh */
whereLoopAddOr(WhereLoopBuilder * pBuilder,Bitmask mPrereq,Bitmask mUnusable)41264f20cd40Sdan static int whereLoopAddOr(
41274f20cd40Sdan   WhereLoopBuilder *pBuilder,
4128599d5764Sdrh   Bitmask mPrereq,
41294f20cd40Sdan   Bitmask mUnusable
41304f20cd40Sdan ){
413170d18344Sdrh   WhereInfo *pWInfo = pBuilder->pWInfo;
4132cf8fa7a6Sdrh   WhereClause *pWC;
4133cf8fa7a6Sdrh   WhereLoop *pNew;
4134cf8fa7a6Sdrh   WhereTerm *pTerm, *pWCEnd;
4135cf8fa7a6Sdrh   int rc = SQLITE_OK;
4136cf8fa7a6Sdrh   int iCur;
4137cf8fa7a6Sdrh   WhereClause tempWC;
4138cf8fa7a6Sdrh   WhereLoopBuilder sSubBuild;
41395da73e1aSdan   WhereOrSet sSum, sCur;
41407601294aSdrh   SrcItem *pItem;
4141cf8fa7a6Sdrh 
4142cf8fa7a6Sdrh   pWC = pBuilder->pWC;
4143cf8fa7a6Sdrh   pWCEnd = pWC->a + pWC->nTerm;
4144cf8fa7a6Sdrh   pNew = pBuilder->pNew;
414577dfd5bbSdrh   memset(&sSum, 0, sizeof(sSum));
4146186ad8ccSdrh   pItem = pWInfo->pTabList->a + pNew->iTab;
4147186ad8ccSdrh   iCur = pItem->iCursor;
4148cf8fa7a6Sdrh 
414961dac44eSdrh   /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */
415061dac44eSdrh   if( pItem->fg.jointype & JT_RIGHT ) return SQLITE_OK;
415161dac44eSdrh 
4152cf8fa7a6Sdrh   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
4153cf8fa7a6Sdrh     if( (pTerm->eOperator & WO_OR)!=0
4154cf8fa7a6Sdrh      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
4155cf8fa7a6Sdrh     ){
4156cf8fa7a6Sdrh       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
4157cf8fa7a6Sdrh       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
4158cf8fa7a6Sdrh       WhereTerm *pOrTerm;
4159aa32e3c6Sdrh       int once = 1;
4160aa32e3c6Sdrh       int i, j;
4161cf8fa7a6Sdrh 
4162783dece5Sdrh       sSubBuild = *pBuilder;
4163aa32e3c6Sdrh       sSubBuild.pOrSet = &sCur;
4164cf8fa7a6Sdrh 
41650a99ba3bSdrh       WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
4166c7f0d229Sdrh       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
4167cf8fa7a6Sdrh         if( (pOrTerm->eOperator & WO_AND)!=0 ){
4168cf8fa7a6Sdrh           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
4169cf8fa7a6Sdrh         }else if( pOrTerm->leftCursor==iCur ){
417070d18344Sdrh           tempWC.pWInfo = pWC->pWInfo;
4171783dece5Sdrh           tempWC.pOuter = pWC;
4172783dece5Sdrh           tempWC.op = TK_AND;
4173783dece5Sdrh           tempWC.nTerm = 1;
4174132f96fcSdrh           tempWC.nBase = 1;
4175cf8fa7a6Sdrh           tempWC.a = pOrTerm;
4176cf8fa7a6Sdrh           sSubBuild.pWC = &tempWC;
4177cf8fa7a6Sdrh         }else{
4178cf8fa7a6Sdrh           continue;
4179cf8fa7a6Sdrh         }
4180aa32e3c6Sdrh         sCur.n = 0;
41815265149cSdrh #ifdef WHERETRACE_ENABLED
41820a99ba3bSdrh         WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
41830a99ba3bSdrh                    (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
41840a99ba3bSdrh         if( sqlite3WhereTrace & 0x400 ){
4185c84a4020Sdrh           sqlite3WhereClausePrint(sSubBuild.pWC);
41865265149cSdrh         }
41875265149cSdrh #endif
41888636e9c5Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
4189cf8fa7a6Sdrh         if( IsVirtual(pItem->pTab) ){
4190599d5764Sdrh           rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
41918636e9c5Sdrh         }else
41928636e9c5Sdrh #endif
41938636e9c5Sdrh         {
4194599d5764Sdrh           rc = whereLoopAddBtree(&sSubBuild, mPrereq);
4195cf8fa7a6Sdrh         }
419636be4c49Sdrh         if( rc==SQLITE_OK ){
4197599d5764Sdrh           rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
419836be4c49Sdrh         }
419919c16c87Sdrh         assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0
420019c16c87Sdrh                 || rc==SQLITE_NOMEM );
420119c16c87Sdrh         testcase( rc==SQLITE_NOMEM && sCur.n>0 );
42029a1f2e48Sdrh         testcase( rc==SQLITE_DONE );
4203aa32e3c6Sdrh         if( sCur.n==0 ){
4204aa32e3c6Sdrh           sSum.n = 0;
4205aa32e3c6Sdrh           break;
4206aa32e3c6Sdrh         }else if( once ){
4207aa32e3c6Sdrh           whereOrMove(&sSum, &sCur);
4208aa32e3c6Sdrh           once = 0;
4209aa32e3c6Sdrh         }else{
42105da73e1aSdan           WhereOrSet sPrev;
4211aa32e3c6Sdrh           whereOrMove(&sPrev, &sSum);
4212aa32e3c6Sdrh           sSum.n = 0;
4213aa32e3c6Sdrh           for(i=0; i<sPrev.n; i++){
4214aa32e3c6Sdrh             for(j=0; j<sCur.n; j++){
4215aa32e3c6Sdrh               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
4216bf539c4dSdrh                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
4217bf539c4dSdrh                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
4218cf8fa7a6Sdrh             }
4219aa32e3c6Sdrh           }
4220aa32e3c6Sdrh         }
4221aa32e3c6Sdrh       }
42224efc9298Sdrh       pNew->nLTerm = 1;
42234efc9298Sdrh       pNew->aLTerm[0] = pTerm;
4224cf8fa7a6Sdrh       pNew->wsFlags = WHERE_MULTI_OR;
4225b8a8e8a5Sdrh       pNew->rSetup = 0;
4226aa32e3c6Sdrh       pNew->iSortIdx = 0;
422723f98daaSdrh       memset(&pNew->u, 0, sizeof(pNew->u));
4228aa32e3c6Sdrh       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
42295da73e1aSdan         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
42305da73e1aSdan         ** of all sub-scans required by the OR-scan. However, due to rounding
42315da73e1aSdan         ** errors, it may be that the cost of the OR-scan is equal to its
42325da73e1aSdan         ** most expensive sub-scan. Add the smallest possible penalty
42335da73e1aSdan         ** (equivalent to multiplying the cost by 1.07) to ensure that
42345da73e1aSdan         ** this does not happen. Otherwise, for WHERE clauses such as the
42355da73e1aSdan         ** following where there is an index on "y":
42365da73e1aSdan         **
42375da73e1aSdan         **     WHERE likelihood(x=?, 0.99) OR y=?
42385da73e1aSdan         **
42395da73e1aSdan         ** the planner may elect to "OR" together a full-table scan and an
42405da73e1aSdan         ** index lookup. And other similarly odd results.  */
42415da73e1aSdan         pNew->rRun = sSum.a[i].rRun + 1;
4242aa32e3c6Sdrh         pNew->nOut = sSum.a[i].nOut;
4243aa32e3c6Sdrh         pNew->prereq = sSum.a[i].prereq;
4244cf8fa7a6Sdrh         rc = whereLoopInsert(pBuilder, pNew);
4245fd5874d2Sdrh       }
42460a99ba3bSdrh       WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
424713e11b43Sdrh     }
424813e11b43Sdrh   }
4249cf8fa7a6Sdrh   return rc;
4250cf8fa7a6Sdrh }
4251cf8fa7a6Sdrh 
4252cf8fa7a6Sdrh /*
4253f1b5f5b8Sdrh ** Add all WhereLoop objects for all tables
4254f1b5f5b8Sdrh */
whereLoopAddAll(WhereLoopBuilder * pBuilder)42555346e95dSdrh static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
425670d18344Sdrh   WhereInfo *pWInfo = pBuilder->pWInfo;
4257599d5764Sdrh   Bitmask mPrereq = 0;
4258f1b5f5b8Sdrh   Bitmask mPrior = 0;
4259f1b5f5b8Sdrh   int iTab;
426070d18344Sdrh   SrcList *pTabList = pWInfo->pTabList;
42617601294aSdrh   SrcItem *pItem;
42627601294aSdrh   SrcItem *pEnd = &pTabList->a[pWInfo->nLevel];
426370d18344Sdrh   sqlite3 *db = pWInfo->pParse->db;
42645346e95dSdrh   int rc = SQLITE_OK;
42657bfbd250Sdrh   int bFirstPastRJ = 0;
426602cb3ff0Sdrh   int hasRightJoin = 0;
4267b8a8e8a5Sdrh   WhereLoop *pNew;
4268f1b5f5b8Sdrh 
42697bfbd250Sdrh 
4270f1b5f5b8Sdrh   /* Loop over the tables in the join, from left to right */
4271b8a8e8a5Sdrh   pNew = pBuilder->pNew;
42725f289e84Sdrh 
42735f289e84Sdrh   /* Verify that pNew has already been initialized */
42745f289e84Sdrh   assert( pNew->nLTerm==0 );
42755f289e84Sdrh   assert( pNew->wsFlags==0 );
427674879e13Sdrh   assert( pNew->nLSlot>=ArraySize(pNew->aLTermSpace) );
427774879e13Sdrh   assert( pNew->aLTerm!=0 );
42785f289e84Sdrh 
42796fb5d358Sdrh   pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
42804f20cd40Sdan   for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
42814f20cd40Sdan     Bitmask mUnusable = 0;
4282b2a90f09Sdrh     pNew->iTab = iTab;
42836fb5d358Sdrh     pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
42846f82e85aSdrh     pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
4285436c28a2Sdrh     if( bFirstPastRJ
4286436c28a2Sdrh      || (pItem->fg.jointype & (JT_OUTER|JT_CROSS|JT_LTORJ))!=0
4287436c28a2Sdrh     ){
42887bfbd250Sdrh       /* Add prerequisites to prevent reordering of FROM clause terms
42897bfbd250Sdrh       ** across CROSS joins and outer joins.  The bFirstPastRJ boolean
42907bfbd250Sdrh       ** prevents the right operand of a RIGHT JOIN from being swapped with
4291436c28a2Sdrh       ** other elements even further to the right.
4292436c28a2Sdrh       **
429302cb3ff0Sdrh       ** The JT_LTORJ case and the hasRightJoin flag work together to
429402cb3ff0Sdrh       ** prevent FROM-clause terms from moving from the right side of
429502cb3ff0Sdrh       ** a LEFT JOIN over to the left side of that join if the LEFT JOIN
429602cb3ff0Sdrh       ** is itself on the left side of a RIGHT JOIN.
4297436c28a2Sdrh       */
429802cb3ff0Sdrh       if( pItem->fg.jointype & JT_LTORJ ) hasRightJoin = 1;
4299367c146bSdrh       mPrereq |= mPrior;
43007bfbd250Sdrh       bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0;
430102cb3ff0Sdrh     }else if( !hasRightJoin ){
430202cb3ff0Sdrh       mPrereq = 0;
4303f1b5f5b8Sdrh     }
4304ec593592Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
4305b2a90f09Sdrh     if( IsVirtual(pItem->pTab) ){
43067601294aSdrh       SrcItem *p;
43074f20cd40Sdan       for(p=&pItem[1]; p<pEnd; p++){
4308a76ac88aSdrh         if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
43094f20cd40Sdan           mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
43104f20cd40Sdan         }
43114f20cd40Sdan       }
4312599d5764Sdrh       rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
4313ec593592Sdrh     }else
4314ec593592Sdrh #endif /* SQLITE_OMIT_VIRTUALTABLE */
4315ec593592Sdrh     {
4316599d5764Sdrh       rc = whereLoopAddBtree(pBuilder, mPrereq);
4317b2a90f09Sdrh     }
4318da230bd4Sdrh     if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
4319599d5764Sdrh       rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
4320b2a90f09Sdrh     }
4321b2a90f09Sdrh     mPrior |= pNew->maskSelf;
4322fc9098a4Sdrh     if( rc || db->mallocFailed ){
4323fc9098a4Sdrh       if( rc==SQLITE_DONE ){
4324fc9098a4Sdrh         /* We hit the query planner search limit set by iPlanLimit */
43257ebb605cSdrh         sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
4326fc9098a4Sdrh         rc = SQLITE_OK;
4327fc9098a4Sdrh       }else{
4328fc9098a4Sdrh         break;
4329fc9098a4Sdrh       }
4330fc9098a4Sdrh     }
4331f1b5f5b8Sdrh   }
43324f20cd40Sdan 
4333a2014159Sdrh   whereLoopClear(db, pNew);
43345346e95dSdrh   return rc;
4335f1b5f5b8Sdrh }
4336f1b5f5b8Sdrh 
4337a18f3d27Sdrh /*
4338c04ea80fSdrh ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
4339319f677dSdrh ** parameters) to see if it outputs rows in the requested ORDER BY
43400401acecSdrh ** (or GROUP BY) without requiring a separate sort operation.  Return N:
4341319f677dSdrh **
43420401acecSdrh **   N>0:   N terms of the ORDER BY clause are satisfied
43430401acecSdrh **   N==0:  No terms of the ORDER BY clause are satisfied
43440401acecSdrh **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.
4345319f677dSdrh **
43469443342eSdrh ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
43479443342eSdrh ** strict.  With GROUP BY and DISTINCT the only requirement is that
43489443342eSdrh ** equivalent rows appear immediately adjacent to one another.  GROUP BY
4349374cd78cSdan ** and DISTINCT do not require rows to appear in any particular order as long
435060ec914cSpeter.d.reid ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
43519443342eSdrh ** the pOrderBy terms can be matched in any order.  With ORDER BY, the
43529443342eSdrh ** pOrderBy terms must be matched in strict left-to-right order.
43536b7157bbSdrh */
wherePathSatisfiesOrderBy(WhereInfo * pWInfo,ExprList * pOrderBy,WherePath * pPath,u16 wctrlFlags,u16 nLoop,WhereLoop * pLast,Bitmask * pRevMask)43540401acecSdrh static i8 wherePathSatisfiesOrderBy(
43556b7157bbSdrh   WhereInfo *pWInfo,    /* The WHERE clause */
43564f402f26Sdrh   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
43576b7157bbSdrh   WherePath *pPath,     /* The WherePath to check */
4358d711e522Sdrh   u16 wctrlFlags,       /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
43594f402f26Sdrh   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
4360319f677dSdrh   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
43614f402f26Sdrh   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
43626b7157bbSdrh ){
436388da644fSdrh   u8 revSet;            /* True if rev is known */
436488da644fSdrh   u8 rev;               /* Composite sort order */
436588da644fSdrh   u8 revIdx;            /* Index sort order */
4366e353ee38Sdrh   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
4367e353ee38Sdrh   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
4368e353ee38Sdrh   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
4369d711e522Sdrh   u16 eqOpMask;         /* Allowed equality operators */
4370416846a3Sdrh   u16 nKeyCol;          /* Number of key columns in pIndex */
4371416846a3Sdrh   u16 nColumn;          /* Total number of ordered columns in the index */
43727699d1c4Sdrh   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
43737699d1c4Sdrh   int iLoop;            /* Index of WhereLoop in pPath being processed */
43747699d1c4Sdrh   int i, j;             /* Loop counters */
43757699d1c4Sdrh   int iCur;             /* Cursor number for current WhereLoop */
43767699d1c4Sdrh   int iColumn;          /* A column number within table iCur */
4377e8ae583eSdrh   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
43787699d1c4Sdrh   WhereTerm *pTerm;     /* A single term of the WHERE clause */
43797699d1c4Sdrh   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
43807699d1c4Sdrh   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
43817699d1c4Sdrh   Index *pIndex;        /* The index associated with pLoop */
43827699d1c4Sdrh   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
43837699d1c4Sdrh   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
43847699d1c4Sdrh   Bitmask obDone;       /* Mask of all ORDER BY terms */
4385e353ee38Sdrh   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
4386b8916be9Sdrh   Bitmask ready;              /* Mask of inner loops */
4387319f677dSdrh 
4388319f677dSdrh   /*
43897699d1c4Sdrh   ** We say the WhereLoop is "one-row" if it generates no more than one
43907699d1c4Sdrh   ** row of output.  A WhereLoop is one-row if all of the following are true:
4391319f677dSdrh   **  (a) All index columns match with WHERE_COLUMN_EQ.
4392319f677dSdrh   **  (b) The index is unique
43937699d1c4Sdrh   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
43947699d1c4Sdrh   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
4395319f677dSdrh   **
4396e353ee38Sdrh   ** We say the WhereLoop is "order-distinct" if the set of columns from
4397e353ee38Sdrh   ** that WhereLoop that are in the ORDER BY clause are different for every
4398e353ee38Sdrh   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
4399e353ee38Sdrh   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
4400e353ee38Sdrh   ** is not order-distinct. To be order-distinct is not quite the same as being
4401e353ee38Sdrh   ** UNIQUE since a UNIQUE column or index can have multiple rows that
4402e353ee38Sdrh   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
4403e353ee38Sdrh   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
4404e353ee38Sdrh   **
4405e353ee38Sdrh   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
4406e353ee38Sdrh   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
4407e353ee38Sdrh   ** automatically order-distinct.
4408319f677dSdrh   */
4409319f677dSdrh 
4410319f677dSdrh   assert( pOrderBy!=0 );
44117699d1c4Sdrh   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
4412319f677dSdrh 
4413319f677dSdrh   nOrderBy = pOrderBy->nExpr;
44147963b0e8Sdrh   testcase( nOrderBy==BMS-1 );
4415e353ee38Sdrh   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
4416e353ee38Sdrh   isOrderDistinct = 1;
44177699d1c4Sdrh   obDone = MASKBIT(nOrderBy)-1;
4418e353ee38Sdrh   orderDistinctMask = 0;
4419b8916be9Sdrh   ready = 0;
4420d711e522Sdrh   eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
4421413b94afSdrh   if( wctrlFlags & (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MAX|WHERE_ORDERBY_MIN) ){
4422413b94afSdrh     eqOpMask |= WO_IN;
4423413b94afSdrh   }
4424e353ee38Sdrh   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
4425b8916be9Sdrh     if( iLoop>0 ) ready |= pLoop->maskSelf;
4426d711e522Sdrh     if( iLoop<nLoop ){
4427d711e522Sdrh       pLoop = pPath->aLoop[iLoop];
4428d711e522Sdrh       if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
4429d711e522Sdrh     }else{
4430d711e522Sdrh       pLoop = pLast;
4431d711e522Sdrh     }
44329dfaf621Sdrh     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
4433ece092e7Sdan       if( pLoop->u.vtab.isOrdered
4434ece092e7Sdan        && ((wctrlFlags&(WHERE_DISTINCTBY|WHERE_SORTBYGROUP))!=WHERE_DISTINCTBY)
4435ece092e7Sdan       ){
4436ff1032e5Sdrh         obSat = obDone;
4437ff1032e5Sdrh       }
44389dfaf621Sdrh       break;
4439a79a0e73Sdan     }else if( wctrlFlags & WHERE_DISTINCTBY ){
4440a79a0e73Sdan       pLoop->u.btree.nDistinctCol = 0;
44419dfaf621Sdrh     }
44427699d1c4Sdrh     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
4443b8916be9Sdrh 
4444b8916be9Sdrh     /* Mark off any ORDER BY term X that is a column in the table of
4445b8916be9Sdrh     ** the current loop for which there is term in the WHERE
4446b8916be9Sdrh     ** clause of the form X IS NULL or X=? that reference only outer
4447b8916be9Sdrh     ** loops.
4448b8916be9Sdrh     */
4449b8916be9Sdrh     for(i=0; i<nOrderBy; i++){
4450b8916be9Sdrh       if( MASKBIT(i) & obSat ) continue;
44510d950af3Sdrh       pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
4452235667a8Sdrh       if( NEVER(pOBExpr==0) ) continue;
44534fcb30b7Sdan       if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
4454b8916be9Sdrh       if( pOBExpr->iTable!=iCur ) continue;
44556f82e85aSdrh       pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
4456d711e522Sdrh                        ~ready, eqOpMask, 0);
4457b8916be9Sdrh       if( pTerm==0 ) continue;
445857a8c615Sdrh       if( pTerm->eOperator==WO_IN ){
445957a8c615Sdrh         /* IN terms are only valid for sorting in the ORDER BY LIMIT
446057a8c615Sdrh         ** optimization, and then only if they are actually used
446157a8c615Sdrh         ** by the query plan */
44626e4b140eSdrh         assert( wctrlFlags &
44636e4b140eSdrh                (WHERE_ORDERBY_LIMIT|WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) );
446457a8c615Sdrh         for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
446557a8c615Sdrh         if( j>=pLoop->nLTerm ) continue;
446657a8c615Sdrh       }
4467e8d0c61fSdrh       if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
446841aa442cSdan         Parse *pParse = pWInfo->pParse;
446941aa442cSdan         CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
447041aa442cSdan         CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
447177c9b3ccSdrh         assert( pColl1 );
447241aa442cSdan         if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
447370efa84dSdrh           continue;
447470efa84dSdrh         }
4475e0cc3c29Sdrh         testcase( pTerm->pExpr->op==TK_IS );
4476b8916be9Sdrh       }
4477b8916be9Sdrh       obSat |= MASKBIT(i);
4478b8916be9Sdrh     }
4479b8916be9Sdrh 
44807699d1c4Sdrh     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
4481319f677dSdrh       if( pLoop->wsFlags & WHERE_IPK ){
4482319f677dSdrh         pIndex = 0;
4483bbbdc83bSdrh         nKeyCol = 0;
4484416846a3Sdrh         nColumn = 1;
4485ef866376Sdrh       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
4486319f677dSdrh         return 0;
44876b7157bbSdrh       }else{
4488bbbdc83bSdrh         nKeyCol = pIndex->nKeyCol;
4489416846a3Sdrh         nColumn = pIndex->nColumn;
4490416846a3Sdrh         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
44914b92f98cSdrh         assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
44924b92f98cSdrh                           || !HasRowid(pIndex->pTable));
44938ed8ddf7Sdrh         /* All relevant terms of the index must also be non-NULL in order
44948ed8ddf7Sdrh         ** for isOrderDistinct to be true.  So the isOrderDistint value
44958ed8ddf7Sdrh         ** computed here might be a false positive.  Corrections will be
44968ed8ddf7Sdrh         ** made at tag-20210426-1 below */
44972ad07d96Sdrh         isOrderDistinct = IsUniqueIndex(pIndex)
44982ad07d96Sdrh                           && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
4499319f677dSdrh       }
45007699d1c4Sdrh 
45017699d1c4Sdrh       /* Loop through all columns of the index and deal with the ones
45027699d1c4Sdrh       ** that are not constrained by == or IN.
45037699d1c4Sdrh       */
45047699d1c4Sdrh       rev = revSet = 0;
4505e353ee38Sdrh       distinctColumns = 0;
4506416846a3Sdrh       for(j=0; j<nColumn; j++){
4507d49fd4e8Sdan         u8 bOnce = 1; /* True to run the ORDER BY search loop */
45087699d1c4Sdrh 
4509d49fd4e8Sdan         assert( j>=pLoop->u.btree.nEq
4510d49fd4e8Sdan             || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
4511d49fd4e8Sdan         );
4512d49fd4e8Sdan         if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
4513d49fd4e8Sdan           u16 eOp = pLoop->aLTerm[j]->eOperator;
4514d49fd4e8Sdan 
4515d49fd4e8Sdan           /* Skip over == and IS and ISNULL terms.  (Also skip IN terms when
4516f7c92e82Sdan           ** doing WHERE_ORDERBY_LIMIT processing).  Except, IS and ISNULL
4517f7c92e82Sdan           ** terms imply that the index is not UNIQUE NOT NULL in which case
4518f7c92e82Sdan           ** the loop need to be marked as not order-distinct because it can
4519f7c92e82Sdan           ** have repeated NULL rows.
4520d49fd4e8Sdan           **
4521d49fd4e8Sdan           ** If the current term is a column of an ((?,?) IN (SELECT...))
4522d49fd4e8Sdan           ** expression for which the SELECT returns more than one column,
4523d49fd4e8Sdan           ** check that it is the only column used by this loop. Otherwise,
4524d49fd4e8Sdan           ** if it is one of two or more, none of the columns can be
4525f7c92e82Sdan           ** considered to match an ORDER BY term.
4526f7c92e82Sdan           */
4527d49fd4e8Sdan           if( (eOp & eqOpMask)!=0 ){
4528f7c92e82Sdan             if( eOp & (WO_ISNULL|WO_IS) ){
4529f7c92e82Sdan               testcase( eOp & WO_ISNULL );
4530f7c92e82Sdan               testcase( eOp & WO_IS );
45317963b0e8Sdrh               testcase( isOrderDistinct );
45327963b0e8Sdrh               isOrderDistinct = 0;
45337963b0e8Sdrh             }
4534e353ee38Sdrh             continue;
453564bcb8cfSdrh           }else if( ALWAYS(eOp & WO_IN) ){
453664bcb8cfSdrh             /* ALWAYS() justification: eOp is an equality operator due to the
453764bcb8cfSdrh             ** j<pLoop->u.btree.nEq constraint above.  Any equality other
453864bcb8cfSdrh             ** than WO_IN is captured by the previous "if".  So this one
453964bcb8cfSdrh             ** always has to be WO_IN. */
4540d49fd4e8Sdan             Expr *pX = pLoop->aLTerm[j]->pExpr;
4541d49fd4e8Sdan             for(i=j+1; i<pLoop->u.btree.nEq; i++){
4542d49fd4e8Sdan               if( pLoop->aLTerm[i]->pExpr==pX ){
4543d49fd4e8Sdan                 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
4544d49fd4e8Sdan                 bOnce = 0;
4545d49fd4e8Sdan                 break;
4546d49fd4e8Sdan               }
4547d49fd4e8Sdan             }
4548d49fd4e8Sdan           }
45497699d1c4Sdrh         }
45507699d1c4Sdrh 
4551e353ee38Sdrh         /* Get the column number in the table (iColumn) and sort order
4552e353ee38Sdrh         ** (revIdx) for the j-th column of the index.
45537699d1c4Sdrh         */
4554416846a3Sdrh         if( pIndex ){
4555319f677dSdrh           iColumn = pIndex->aiColumn[j];
455615750a26Sdan           revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
4557488e6191Sdrh           if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
455888da644fSdrh         }else{
45594b92f98cSdrh           iColumn = XN_ROWID;
456088da644fSdrh           revIdx = 0;
456188da644fSdrh         }
45627699d1c4Sdrh 
45637699d1c4Sdrh         /* An unconstrained column that might be NULL means that this
45648ed8ddf7Sdrh         ** WhereLoop is not well-ordered.  tag-20210426-1
45657699d1c4Sdrh         */
45668ed8ddf7Sdrh         if( isOrderDistinct ){
45678ed8ddf7Sdrh           if( iColumn>=0
45687699d1c4Sdrh            && j>=pLoop->u.btree.nEq
45697699d1c4Sdrh            && pIndex->pTable->aCol[iColumn].notNull==0
45707699d1c4Sdrh           ){
4571e353ee38Sdrh             isOrderDistinct = 0;
45721b0f026dSdrh           }
45738ed8ddf7Sdrh           if( iColumn==XN_EXPR ){
45748ed8ddf7Sdrh             isOrderDistinct = 0;
45758ed8ddf7Sdrh           }
45768ed8ddf7Sdrh         }
45777699d1c4Sdrh 
45787699d1c4Sdrh         /* Find the ORDER BY term that corresponds to the j-th column
4579374cd78cSdan         ** of the index and mark that ORDER BY term off
45807699d1c4Sdrh         */
4581e353ee38Sdrh         isMatch = 0;
45827699d1c4Sdrh         for(i=0; bOnce && i<nOrderBy; i++){
45837699d1c4Sdrh           if( MASKBIT(i) & obSat ) continue;
45840d950af3Sdrh           pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
458593ec45d5Sdrh           testcase( wctrlFlags & WHERE_GROUPBY );
458693ec45d5Sdrh           testcase( wctrlFlags & WHERE_DISTINCTBY );
4587235667a8Sdrh           if( NEVER(pOBExpr==0) ) continue;
45884f402f26Sdrh           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
4589488e6191Sdrh           if( iColumn>=XN_ROWID ){
45904fcb30b7Sdan             if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
45917699d1c4Sdrh             if( pOBExpr->iTable!=iCur ) continue;
45927699d1c4Sdrh             if( pOBExpr->iColumn!=iColumn ) continue;
4593dae26fe5Sdrh           }else{
4594db8e68b4Sdrh             Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
4595db8e68b4Sdrh             if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
4596dae26fe5Sdrh               continue;
4597dae26fe5Sdrh             }
4598dae26fe5Sdrh           }
459962f6f51aSdan           if( iColumn!=XN_ROWID ){
460070efa84dSdrh             pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
46017699d1c4Sdrh             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
460288da644fSdrh           }
4603a79a0e73Sdan           if( wctrlFlags & WHERE_DISTINCTBY ){
4604a79a0e73Sdan             pLoop->u.btree.nDistinctCol = j+1;
4605a79a0e73Sdan           }
4606e353ee38Sdrh           isMatch = 1;
46077699d1c4Sdrh           break;
4608dc3cd4b0Sdrh         }
46094929047dSdrh         if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
4610e353ee38Sdrh           /* Make sure the sort order is compatible in an ORDER BY clause.
4611e353ee38Sdrh           ** Sort order is irrelevant for a GROUP BY clause. */
4612319f677dSdrh           if( revSet ){
4613d88fd539Sdrh             if( (rev ^ revIdx)
4614d88fd539Sdrh                            != (pOrderBy->a[i].fg.sortFlags&KEYINFO_ORDER_DESC)
4615d88fd539Sdrh             ){
461615750a26Sdan               isMatch = 0;
461715750a26Sdan             }
4618319f677dSdrh           }else{
4619d88fd539Sdrh             rev = revIdx ^ (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC);
46207699d1c4Sdrh             if( rev ) *pRevMask |= MASKBIT(iLoop);
4621319f677dSdrh             revSet = 1;
4622319f677dSdrh           }
4623319f677dSdrh         }
4624d88fd539Sdrh         if( isMatch && (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL) ){
462515750a26Sdan           if( j==pLoop->u.btree.nEq ){
462615750a26Sdan             pLoop->wsFlags |= WHERE_BIGNULL_SORT;
462715750a26Sdan           }else{
462815750a26Sdan             isMatch = 0;
462915750a26Sdan           }
463015750a26Sdan         }
463159b8f2e1Sdrh         if( isMatch ){
463290b2fe6bSdan           if( iColumn==XN_ROWID ){
463359b8f2e1Sdrh             testcase( distinctColumns==0 );
463459b8f2e1Sdrh             distinctColumns = 1;
463559b8f2e1Sdrh           }
463659b8f2e1Sdrh           obSat |= MASKBIT(i);
46377699d1c4Sdrh         }else{
46387699d1c4Sdrh           /* No match found */
4639bbbdc83bSdrh           if( j==0 || j<nKeyCol ){
46407963b0e8Sdrh             testcase( isOrderDistinct!=0 );
46417963b0e8Sdrh             isOrderDistinct = 0;
46427963b0e8Sdrh           }
46437699d1c4Sdrh           break;
46447699d1c4Sdrh         }
46457699d1c4Sdrh       } /* end Loop over all index columns */
464681186b43Sdrh       if( distinctColumns ){
464781186b43Sdrh         testcase( isOrderDistinct==0 );
464881186b43Sdrh         isOrderDistinct = 1;
464981186b43Sdrh       }
46507699d1c4Sdrh     } /* end-if not one-row */
46517699d1c4Sdrh 
46527699d1c4Sdrh     /* Mark off any other ORDER BY terms that reference pLoop */
4653e353ee38Sdrh     if( isOrderDistinct ){
4654e353ee38Sdrh       orderDistinctMask |= pLoop->maskSelf;
46557699d1c4Sdrh       for(i=0; i<nOrderBy; i++){
46567699d1c4Sdrh         Expr *p;
4657434a9314Sdrh         Bitmask mTerm;
46587699d1c4Sdrh         if( MASKBIT(i) & obSat ) continue;
46597699d1c4Sdrh         p = pOrderBy->a[i].pExpr;
46606c1f4ef2Sdrh         mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
4661434a9314Sdrh         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
4662434a9314Sdrh         if( (mTerm&~orderDistinctMask)==0 ){
46637699d1c4Sdrh           obSat |= MASKBIT(i);
46640afb423fSdrh         }
4665dc3cd4b0Sdrh       }
4666319f677dSdrh     }
4667b8916be9Sdrh   } /* End the loop over all WhereLoops from outer-most down to inner-most */
466836ed0342Sdrh   if( obSat==obDone ) return (i8)nOrderBy;
4669d2de861cSdrh   if( !isOrderDistinct ){
4670d2de861cSdrh     for(i=nOrderBy-1; i>0; i--){
4671c59ffa8cSdrh       Bitmask m = ALWAYS(i<BMS) ? MASKBIT(i) - 1 : 0;
4672d2de861cSdrh       if( (obSat&m)==m ) return i;
4673d2de861cSdrh     }
4674d2de861cSdrh     return 0;
4675d2de861cSdrh   }
4676319f677dSdrh   return -1;
4677319f677dSdrh }
46786b7157bbSdrh 
4679374cd78cSdan 
4680374cd78cSdan /*
4681374cd78cSdan ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
4682374cd78cSdan ** the planner assumes that the specified pOrderBy list is actually a GROUP
4683374cd78cSdan ** BY clause - and so any order that groups rows as required satisfies the
4684374cd78cSdan ** request.
4685374cd78cSdan **
4686374cd78cSdan ** Normally, in this case it is not possible for the caller to determine
4687374cd78cSdan ** whether or not the rows are really being delivered in sorted order, or
4688374cd78cSdan ** just in some other order that provides the required grouping. However,
4689374cd78cSdan ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
4690374cd78cSdan ** this function may be called on the returned WhereInfo object. It returns
4691374cd78cSdan ** true if the rows really will be sorted in the specified order, or false
4692374cd78cSdan ** otherwise.
4693374cd78cSdan **
4694374cd78cSdan ** For example, assuming:
4695374cd78cSdan **
4696374cd78cSdan **   CREATE INDEX i1 ON t1(x, Y);
4697374cd78cSdan **
4698374cd78cSdan ** then
4699374cd78cSdan **
4700374cd78cSdan **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
4701374cd78cSdan **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
4702374cd78cSdan */
sqlite3WhereIsSorted(WhereInfo * pWInfo)4703374cd78cSdan int sqlite3WhereIsSorted(WhereInfo *pWInfo){
4704ece092e7Sdan   assert( pWInfo->wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY) );
4705374cd78cSdan   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
4706374cd78cSdan   return pWInfo->sorted;
4707374cd78cSdan }
4708374cd78cSdan 
4709d15cb171Sdrh #ifdef WHERETRACE_ENABLED
4710d15cb171Sdrh /* For debugging use only: */
wherePathName(WherePath * pPath,int nLoop,WhereLoop * pLast)4711d15cb171Sdrh static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
4712d15cb171Sdrh   static char zName[65];
4713d15cb171Sdrh   int i;
4714d15cb171Sdrh   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
4715d15cb171Sdrh   if( pLast ) zName[i++] = pLast->cId;
4716d15cb171Sdrh   zName[i] = 0;
4717d15cb171Sdrh   return zName;
4718d15cb171Sdrh }
4719d15cb171Sdrh #endif
4720d15cb171Sdrh 
47216b7157bbSdrh /*
472250ae31e6Sdan ** Return the cost of sorting nRow rows, assuming that the keys have
472350ae31e6Sdan ** nOrderby columns and that the first nSorted columns are already in
472450ae31e6Sdan ** order.
472550ae31e6Sdan */
whereSortingCost(WhereInfo * pWInfo,LogEst nRow,int nOrderBy,int nSorted)472650ae31e6Sdan static LogEst whereSortingCost(
472750ae31e6Sdan   WhereInfo *pWInfo,
472850ae31e6Sdan   LogEst nRow,
472950ae31e6Sdan   int nOrderBy,
473050ae31e6Sdan   int nSorted
473150ae31e6Sdan ){
473250ae31e6Sdan   /* TUNING: Estimated cost of a full external sort, where N is
473350ae31e6Sdan   ** the number of rows to sort is:
473450ae31e6Sdan   **
473550ae31e6Sdan   **   cost = (3.0 * N * log(N)).
473650ae31e6Sdan   **
473750ae31e6Sdan   ** Or, if the order-by clause has X terms but only the last Y
473850ae31e6Sdan   ** terms are out of order, then block-sorting will reduce the
473950ae31e6Sdan   ** sorting cost to:
474050ae31e6Sdan   **
474150ae31e6Sdan   **   cost = (3.0 * N * log(N)) * (Y/X)
474250ae31e6Sdan   **
474350ae31e6Sdan   ** The (Y/X) term is implemented using stack variable rScale
474458d6f633Sdrh   ** below.
474558d6f633Sdrh   */
474650ae31e6Sdan   LogEst rScale, rSortCost;
474750ae31e6Sdan   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
474850ae31e6Sdan   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
4749c3489bbfSdrh   rSortCost = nRow + rScale + 16;
475050ae31e6Sdan 
4751c3489bbfSdrh   /* Multiple by log(M) where M is the number of output rows.
475258d6f633Sdrh   ** Use the LIMIT for M if it is smaller.  Or if this sort is for
475375e6bbbeSdrh   ** a DISTINCT operator, M will be the number of distinct output
475458d6f633Sdrh   ** rows, so fudge it downwards a bit.
475558d6f633Sdrh   */
47568c098e61Sdrh   if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
47578c098e61Sdrh     nRow = pWInfo->iLimit;
475858d6f633Sdrh   }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
475958d6f633Sdrh     /* TUNING: In the sort for a DISTINCT operator, assume that the DISTINCT
476058d6f633Sdrh     ** reduces the number of output rows by a factor of 2 */
47615f086ddeSdrh     if( nRow>10 ){ nRow -= 10;  assert( 10==sqlite3LogEst(2) ); }
476250ae31e6Sdan   }
4763c3489bbfSdrh   rSortCost += estLog(nRow);
476450ae31e6Sdan   return rSortCost;
476550ae31e6Sdan }
476650ae31e6Sdan 
476750ae31e6Sdan /*
476851576f47Sdan ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
4769a18f3d27Sdrh ** attempts to find the lowest cost path that visits each WhereLoop
4770a18f3d27Sdrh ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
4771a18f3d27Sdrh **
4772c7f0d229Sdrh ** Assume that the total number of output rows that will need to be sorted
4773c7f0d229Sdrh ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
4774c7f0d229Sdrh ** costs if nRowEst==0.
4775c7f0d229Sdrh **
4776a18f3d27Sdrh ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
4777a18f3d27Sdrh ** error occurs.
4778a18f3d27Sdrh */
wherePathSolver(WhereInfo * pWInfo,LogEst nRowEst)4779bf539c4dSdrh static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
4780783dece5Sdrh   int mxChoice;             /* Maximum number of simultaneous paths tracked */
4781a18f3d27Sdrh   int nLoop;                /* Number of terms in the join */
4782e1e2e9acSdrh   Parse *pParse;            /* Parsing context */
4783a18f3d27Sdrh   int iLoop;                /* Loop counter over the terms of the join */
4784a18f3d27Sdrh   int ii, jj;               /* Loop counters */
4785fde1e6bcSdrh   int mxI = 0;              /* Index of next entry to replace */
4786d2de861cSdrh   int nOrderBy;             /* Number of ORDER BY clause terms */
4787bf539c4dSdrh   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
478850ae31e6Sdan   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
4789a18f3d27Sdrh   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
4790a18f3d27Sdrh   WherePath *aFrom;         /* All nFrom paths at the previous level */
4791a18f3d27Sdrh   WherePath *aTo;           /* The nTo best paths at the current level */
4792a18f3d27Sdrh   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
4793a18f3d27Sdrh   WherePath *pTo;           /* An element of aTo[] that we are working on */
4794a18f3d27Sdrh   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
4795a18f3d27Sdrh   WhereLoop **pX;           /* Used to divy up the pSpace memory */
479650ae31e6Sdan   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
4797a18f3d27Sdrh   char *pSpace;             /* Temporary memory used by this routine */
4798e2c27851Sdan   int nSpace;               /* Bytes of space allocated at pSpace */
4799a18f3d27Sdrh 
4800e1e2e9acSdrh   pParse = pWInfo->pParse;
4801a18f3d27Sdrh   nLoop = pWInfo->nLevel;
4802e1e2e9acSdrh   /* TUNING: For simple queries, only the best path is tracked.
4803e1e2e9acSdrh   ** For 2-way joins, the 5 best paths are followed.
4804e1e2e9acSdrh   ** For joins of 3 or more tables, track the 10 best paths */
48052504c6c6Sdrh   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
4806a18f3d27Sdrh   assert( nLoop<=pWInfo->pTabList->nSrc );
4807ddef5dc0Sdrh   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
4808a18f3d27Sdrh 
480950ae31e6Sdan   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
481050ae31e6Sdan   ** case the purpose of this call is to estimate the number of rows returned
481150ae31e6Sdan   ** by the overall query. Once this estimate has been obtained, the caller
481250ae31e6Sdan   ** will invoke this function a second time, passing the estimate as the
481350ae31e6Sdan   ** nRowEst parameter.  */
481450ae31e6Sdan   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
481550ae31e6Sdan     nOrderBy = 0;
481650ae31e6Sdan   }else{
481750ae31e6Sdan     nOrderBy = pWInfo->pOrderBy->nExpr;
481850ae31e6Sdan   }
481950ae31e6Sdan 
482050ae31e6Sdan   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
4821e2c27851Sdan   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
4822e2c27851Sdan   nSpace += sizeof(LogEst) * nOrderBy;
4823ce4b0fdfSdrh   pSpace = sqlite3StackAllocRawNN(pParse->db, nSpace);
4824fad3039cSmistachkin   if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
4825a18f3d27Sdrh   aTo = (WherePath*)pSpace;
4826a18f3d27Sdrh   aFrom = aTo+mxChoice;
4827a18f3d27Sdrh   memset(aFrom, 0, sizeof(aFrom[0]));
4828a18f3d27Sdrh   pX = (WhereLoop**)(aFrom+mxChoice);
4829e9d935a8Sdrh   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
4830a18f3d27Sdrh     pFrom->aLoop = pX;
4831a18f3d27Sdrh   }
483250ae31e6Sdan   if( nOrderBy ){
483350ae31e6Sdan     /* If there is an ORDER BY clause and it is not being ignored, set up
483450ae31e6Sdan     ** space for the aSortCost[] array. Each element of the aSortCost array
483550ae31e6Sdan     ** is either zero - meaning it has not yet been initialized - or the
483650ae31e6Sdan     ** cost of sorting nRowEst rows of data where the first X terms of
483750ae31e6Sdan     ** the ORDER BY clause are already in order, where X is the array
483850ae31e6Sdan     ** index.  */
483950ae31e6Sdan     aSortCost = (LogEst*)pX;
4840e2c27851Sdan     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
484150ae31e6Sdan   }
4842e2c27851Sdan   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
4843e2c27851Sdan   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
4844a18f3d27Sdrh 
4845e1e2e9acSdrh   /* Seed the search with a single WherePath containing zero WhereLoops.
4846e1e2e9acSdrh   **
4847f104abbaSdan   ** TUNING: Do not let the number of iterations go above 28.  If the cost
4848f104abbaSdan   ** of computing an automatic index is not paid back within the first 28
4849e1e2e9acSdrh   ** rows, then do not use the automatic index. */
4850f104abbaSdan   aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
4851a18f3d27Sdrh   nFrom = 1;
485250ae31e6Sdan   assert( aFrom[0].isOrdered==0 );
485350ae31e6Sdan   if( nOrderBy ){
485450ae31e6Sdan     /* If nLoop is zero, then there are no FROM terms in the query. Since
485550ae31e6Sdan     ** in this case the query may return a maximum of one row, the results
485650ae31e6Sdan     ** are already in the requested order. Set isOrdered to nOrderBy to
485750ae31e6Sdan     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
485850ae31e6Sdan     ** -1, indicating that the result set may or may not be ordered,
485950ae31e6Sdan     ** depending on the loops added to the current plan.  */
486050ae31e6Sdan     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
48616b7157bbSdrh   }
48626b7157bbSdrh 
48636b7157bbSdrh   /* Compute successively longer WherePaths using the previous generation
48646b7157bbSdrh   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
48656b7157bbSdrh   ** best paths at each generation */
4866a18f3d27Sdrh   for(iLoop=0; iLoop<nLoop; iLoop++){
4867a18f3d27Sdrh     nTo = 0;
4868a18f3d27Sdrh     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
4869a18f3d27Sdrh       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
487050ae31e6Sdan         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
487150ae31e6Sdan         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
487250ae31e6Sdan         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
487372f38795Sdrh         i8 isOrdered;                     /* isOrdered for (pFrom+pWLoop) */
487450ae31e6Sdan         Bitmask maskNew;                  /* Mask of src visited by (..) */
487572f38795Sdrh         Bitmask revMask;                  /* Mask of rev-order loops for (..) */
487650ae31e6Sdan 
4877a18f3d27Sdrh         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
4878a18f3d27Sdrh         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
4879492ad131Sdrh         if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
48805a6f5edeSdrh           /* Do not use an automatic index if the this loop is expected
4881492ad131Sdrh           ** to run less than 1.25 times.  It is tempting to also exclude
4882492ad131Sdrh           ** automatic index usage on an outer loop, but sometimes an automatic
4883492ad131Sdrh           ** index is useful in the outer loop of a correlated subquery. */
48845a6f5edeSdrh           assert( 10==sqlite3LogEst(2) );
488587eb919dSdrh           continue;
488687eb919dSdrh         }
4887492ad131Sdrh 
48886b7157bbSdrh         /* At this point, pWLoop is a candidate to be the next loop.
48896b7157bbSdrh         ** Compute its cost */
489050ae31e6Sdan         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
489150ae31e6Sdan         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
4892fde1e6bcSdrh         nOut = pFrom->nRow + pWLoop->nOut;
4893a18f3d27Sdrh         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
489472f38795Sdrh         isOrdered = pFrom->isOrdered;
48950401acecSdrh         if( isOrdered<0 ){
489672f38795Sdrh           revMask = 0;
48970401acecSdrh           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
48984f402f26Sdrh                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
48990401acecSdrh                        iLoop, pWLoop, &revMask);
49003a5ba8b1Sdrh         }else{
49013a5ba8b1Sdrh           revMask = pFrom->revLoop;
49026b7157bbSdrh         }
490350ae31e6Sdan         if( isOrdered>=0 && isOrdered<nOrderBy ){
490450ae31e6Sdan           if( aSortCost[isOrdered]==0 ){
490550ae31e6Sdan             aSortCost[isOrdered] = whereSortingCost(
490650ae31e6Sdan                 pWInfo, nRowEst, nOrderBy, isOrdered
490750ae31e6Sdan             );
490850ae31e6Sdan           }
4909f559ed34Sdrh           /* TUNING:  Add a small extra penalty (5) to sorting as an
4910f559ed34Sdrh           ** extra encouragment to the query planner to select a plan
4911f559ed34Sdrh           ** where the rows emerge in the correct order without any sorting
4912f559ed34Sdrh           ** required. */
4913f559ed34Sdrh           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5;
491450ae31e6Sdan 
491550ae31e6Sdan           WHERETRACE(0x002,
491650ae31e6Sdan               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
491750ae31e6Sdan                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
491850ae31e6Sdan                rUnsorted, rCost));
491950ae31e6Sdan         }else{
492050ae31e6Sdan           rCost = rUnsorted;
492154ac445dSdrh           rUnsorted -= 2;  /* TUNING:  Slight bias in favor of no-sort plans */
492250ae31e6Sdan         }
492350ae31e6Sdan 
4924a3fc683cSdrh         /* TUNING:  A full-scan of a VIEW or subquery in the outer loop
4925a3fc683cSdrh         ** is not so bad. */
4926a3fc683cSdrh         if( iLoop==0 && (pWLoop->wsFlags & WHERE_VIEWSCAN)!=0 ){
4927a3fc683cSdrh           rCost += -10;
4928a3fc683cSdrh           nOut += -30;
4929a3fc683cSdrh         }
4930a3fc683cSdrh 
4931ddef5dc0Sdrh         /* Check to see if pWLoop should be added to the set of
4932ddef5dc0Sdrh         ** mxChoice best-so-far paths.
4933ddef5dc0Sdrh         **
4934ddef5dc0Sdrh         ** First look for an existing path among best-so-far paths
4935ddef5dc0Sdrh         ** that covers the same set of loops and has the same isOrdered
4936ddef5dc0Sdrh         ** setting as the current path candidate.
4937f2a90306Sdrh         **
4938f2a90306Sdrh         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
4939f2a90306Sdrh         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
4940f2a90306Sdrh         ** of legal values for isOrdered, -1..64.
4941ddef5dc0Sdrh         */
49426b7157bbSdrh         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
4943fde1e6bcSdrh           if( pTo->maskLoop==maskNew
4944f2a90306Sdrh            && ((pTo->isOrdered^isOrdered)&0x80)==0
4945fde1e6bcSdrh           ){
49467963b0e8Sdrh             testcase( jj==nTo-1 );
49476b7157bbSdrh             break;
49486b7157bbSdrh           }
49496b7157bbSdrh         }
4950a18f3d27Sdrh         if( jj>=nTo ){
4951ddef5dc0Sdrh           /* None of the existing best-so-far paths match the candidate. */
4952ddef5dc0Sdrh           if( nTo>=mxChoice
495350ae31e6Sdan            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
4954ddef5dc0Sdrh           ){
4955ddef5dc0Sdrh             /* The current candidate is no better than any of the mxChoice
4956ddef5dc0Sdrh             ** paths currently in the best-so-far buffer.  So discard
4957ddef5dc0Sdrh             ** this candidate as not viable. */
4958989578e1Sdrh #ifdef WHERETRACE_ENABLED /* 0x4 */
4959ae70cf18Sdrh             if( sqlite3WhereTrace&0x4 ){
496078436d4cSdrh               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d,%3d order=%c\n",
496178436d4cSdrh                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
49620401acecSdrh                   isOrdered>=0 ? isOrdered+'0' : '?');
4963d15cb171Sdrh             }
4964d15cb171Sdrh #endif
4965d15cb171Sdrh             continue;
4966d15cb171Sdrh           }
4967ddef5dc0Sdrh           /* If we reach this points it means that the new candidate path
4968ddef5dc0Sdrh           ** needs to be added to the set of best-so-far paths. */
4969a18f3d27Sdrh           if( nTo<mxChoice ){
4970d15cb171Sdrh             /* Increase the size of the aTo set by one */
4971a18f3d27Sdrh             jj = nTo++;
4972a18f3d27Sdrh           }else{
4973d15cb171Sdrh             /* New path replaces the prior worst to keep count below mxChoice */
4974fde1e6bcSdrh             jj = mxI;
4975a18f3d27Sdrh           }
4976a18f3d27Sdrh           pTo = &aTo[jj];
4977989578e1Sdrh #ifdef WHERETRACE_ENABLED /* 0x4 */
4978ae70cf18Sdrh           if( sqlite3WhereTrace&0x4 ){
497978436d4cSdrh             sqlite3DebugPrintf("New    %s cost=%-3d,%3d,%3d order=%c\n",
498078436d4cSdrh                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
49810401acecSdrh                 isOrdered>=0 ? isOrdered+'0' : '?');
4982d15cb171Sdrh           }
4983d15cb171Sdrh #endif
4984f204dac1Sdrh         }else{
4985ddef5dc0Sdrh           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
498678436d4cSdrh           ** same set of loops and has the same isOrdered setting as the
4987ddef5dc0Sdrh           ** candidate path.  Check to see if the candidate should replace
498878436d4cSdrh           ** pTo or if the candidate should be skipped.
498978436d4cSdrh           **
499078436d4cSdrh           ** The conditional is an expanded vector comparison equivalent to:
499178436d4cSdrh           **   (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
499278436d4cSdrh           */
499378436d4cSdrh           if( pTo->rCost<rCost
499478436d4cSdrh            || (pTo->rCost==rCost
499578436d4cSdrh                && (pTo->nRow<nOut
499678436d4cSdrh                    || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
499778436d4cSdrh                   )
499878436d4cSdrh               )
499978436d4cSdrh           ){
5000989578e1Sdrh #ifdef WHERETRACE_ENABLED /* 0x4 */
5001ae70cf18Sdrh             if( sqlite3WhereTrace&0x4 ){
5002d15cb171Sdrh               sqlite3DebugPrintf(
500378436d4cSdrh                   "Skip   %s cost=%-3d,%3d,%3d order=%c",
500478436d4cSdrh                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
50050401acecSdrh                   isOrdered>=0 ? isOrdered+'0' : '?');
500678436d4cSdrh               sqlite3DebugPrintf("   vs %s cost=%-3d,%3d,%3d order=%c\n",
5007fde1e6bcSdrh                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
500878436d4cSdrh                   pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5009d15cb171Sdrh             }
5010d15cb171Sdrh #endif
5011ddef5dc0Sdrh             /* Discard the candidate path from further consideration */
50127963b0e8Sdrh             testcase( pTo->rCost==rCost );
5013d15cb171Sdrh             continue;
5014d15cb171Sdrh           }
50157963b0e8Sdrh           testcase( pTo->rCost==rCost+1 );
5016ddef5dc0Sdrh           /* Control reaches here if the candidate path is better than the
5017ddef5dc0Sdrh           ** pTo path.  Replace pTo with the candidate. */
5018989578e1Sdrh #ifdef WHERETRACE_ENABLED /* 0x4 */
5019ae70cf18Sdrh           if( sqlite3WhereTrace&0x4 ){
5020d15cb171Sdrh             sqlite3DebugPrintf(
502178436d4cSdrh                 "Update %s cost=%-3d,%3d,%3d order=%c",
502278436d4cSdrh                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
50230401acecSdrh                 isOrdered>=0 ? isOrdered+'0' : '?');
502478436d4cSdrh             sqlite3DebugPrintf("  was %s cost=%-3d,%3d,%3d order=%c\n",
5025fde1e6bcSdrh                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
502678436d4cSdrh                 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
5027d15cb171Sdrh           }
5028d15cb171Sdrh #endif
5029a18f3d27Sdrh         }
50306b7157bbSdrh         /* pWLoop is a winner.  Add it to the set of best so far */
5031a18f3d27Sdrh         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
5032319f677dSdrh         pTo->revLoop = revMask;
5033fde1e6bcSdrh         pTo->nRow = nOut;
5034a18f3d27Sdrh         pTo->rCost = rCost;
503550ae31e6Sdan         pTo->rUnsorted = rUnsorted;
50366b7157bbSdrh         pTo->isOrdered = isOrdered;
5037a18f3d27Sdrh         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
5038a18f3d27Sdrh         pTo->aLoop[iLoop] = pWLoop;
5039a18f3d27Sdrh         if( nTo>=mxChoice ){
5040fde1e6bcSdrh           mxI = 0;
5041a18f3d27Sdrh           mxCost = aTo[0].rCost;
504250ae31e6Sdan           mxUnsorted = aTo[0].nRow;
5043a18f3d27Sdrh           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
504450ae31e6Sdan             if( pTo->rCost>mxCost
504550ae31e6Sdan              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
504650ae31e6Sdan             ){
5047fde1e6bcSdrh               mxCost = pTo->rCost;
504850ae31e6Sdan               mxUnsorted = pTo->rUnsorted;
5049fde1e6bcSdrh               mxI = jj;
5050fde1e6bcSdrh             }
5051a18f3d27Sdrh           }
5052a18f3d27Sdrh         }
5053a18f3d27Sdrh       }
5054a18f3d27Sdrh     }
5055a18f3d27Sdrh 
5056989578e1Sdrh #ifdef WHERETRACE_ENABLED  /* >=2 */
50571b131b7aSdrh     if( sqlite3WhereTrace & 0x02 ){
5058a50ef114Sdrh       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
5059d15cb171Sdrh       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
5060b8a8e8a5Sdrh         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
5061a50ef114Sdrh            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
50620401acecSdrh            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
50630401acecSdrh         if( pTo->isOrdered>0 ){
506488da644fSdrh           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
506588da644fSdrh         }else{
506688da644fSdrh           sqlite3DebugPrintf("\n");
506788da644fSdrh         }
5068f204dac1Sdrh       }
5069f204dac1Sdrh     }
5070f204dac1Sdrh #endif
5071f204dac1Sdrh 
50726b7157bbSdrh     /* Swap the roles of aFrom and aTo for the next generation */
5073a18f3d27Sdrh     pFrom = aTo;
5074a18f3d27Sdrh     aTo = aFrom;
5075a18f3d27Sdrh     aFrom = pFrom;
5076a18f3d27Sdrh     nFrom = nTo;
5077a18f3d27Sdrh   }
5078a18f3d27Sdrh 
507975b93405Sdrh   if( nFrom==0 ){
5080e1e2e9acSdrh     sqlite3ErrorMsg(pParse, "no query solution");
5081ce4b0fdfSdrh     sqlite3StackFreeNN(pParse->db, pSpace);
508275b93405Sdrh     return SQLITE_ERROR;
508375b93405Sdrh   }
5084a18f3d27Sdrh 
50856b7157bbSdrh   /* Find the lowest cost path.  pFrom will be left pointing to that path */
5086a18f3d27Sdrh   pFrom = aFrom;
5087a18f3d27Sdrh   for(ii=1; ii<nFrom; ii++){
5088a18f3d27Sdrh     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
5089a18f3d27Sdrh   }
5090a18f3d27Sdrh   assert( pWInfo->nLevel==nLoop );
50916b7157bbSdrh   /* Load the lowest cost path into pWInfo */
5092a18f3d27Sdrh   for(iLoop=0; iLoop<nLoop; iLoop++){
50937ba39a92Sdrh     WhereLevel *pLevel = pWInfo->a + iLoop;
50947ba39a92Sdrh     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
5095e217efc8Sdrh     pLevel->iFrom = pWLoop->iTab;
50967ba39a92Sdrh     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
5097a18f3d27Sdrh   }
5098fd636c75Sdrh   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
5099fd636c75Sdrh    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
5100fd636c75Sdrh    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
51014f402f26Sdrh    && nRowEst
51024f402f26Sdrh   ){
51034f402f26Sdrh     Bitmask notUsed;
51046457a353Sdrh     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
510593ec45d5Sdrh                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
51060401acecSdrh     if( rc==pWInfo->pResultSet->nExpr ){
51070401acecSdrh       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
51084f402f26Sdrh     }
51090401acecSdrh   }
51106ee5a7b4Sdrh   pWInfo->bOrderedInnerLoop = 0;
5111079a3072Sdrh   if( pWInfo->pOrderBy ){
5112ece092e7Sdan     pWInfo->nOBSat = pFrom->isOrdered;
51134f402f26Sdrh     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
5114079a3072Sdrh       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
51154f402f26Sdrh         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
5116079a3072Sdrh       }
51174f402f26Sdrh     }else{
511888da644fSdrh       pWInfo->revMask = pFrom->revLoop;
5119a536df4eSdrh       if( pWInfo->nOBSat<=0 ){
5120a536df4eSdrh         pWInfo->nOBSat = 0;
5121c436a03dSdrh         if( nLoop>0 ){
5122c436a03dSdrh           u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
5123c436a03dSdrh           if( (wsFlags & WHERE_ONEROW)==0
512483465a66Sdan            && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
512583465a66Sdan           ){
5126d93ba627Sdan             Bitmask m = 0;
5127d711e522Sdrh             int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
5128d711e522Sdrh                       WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
5129013ae68bSdrh             testcase( wsFlags & WHERE_IPK );
5130013ae68bSdrh             testcase( wsFlags & WHERE_COLUMN_IN );
5131d711e522Sdrh             if( rc==pWInfo->pOrderBy->nExpr ){
5132d711e522Sdrh               pWInfo->bOrderedInnerLoop = 1;
5133d711e522Sdrh               pWInfo->revMask = m;
5134d711e522Sdrh             }
5135d711e522Sdrh           }
5136a536df4eSdrh         }
5137751a44edSdrh       }else if( nLoop
5138751a44edSdrh             && pWInfo->nOBSat==1
5139413b94afSdrh             && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
5140413b94afSdrh             ){
514119543b9bSdrh         pWInfo->bOrderedInnerLoop = 1;
51426b7157bbSdrh       }
5143a18f3d27Sdrh     }
5144374cd78cSdan     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
514511b04817Sdrh         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
5146374cd78cSdan     ){
5147b6453201Sdan       Bitmask revMask = 0;
5148374cd78cSdan       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
5149b6453201Sdan           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
5150374cd78cSdan       );
5151374cd78cSdan       assert( pWInfo->sorted==0 );
5152b6453201Sdan       if( nOrder==pWInfo->pOrderBy->nExpr ){
5153b6453201Sdan         pWInfo->sorted = 1;
5154b6453201Sdan         pWInfo->revMask = revMask;
5155b6453201Sdan       }
51564f402f26Sdrh     }
5157374cd78cSdan   }
5158374cd78cSdan 
5159374cd78cSdan 
5160a50ef114Sdrh   pWInfo->nRowOut = pFrom->nRow;
5161a18f3d27Sdrh 
5162a18f3d27Sdrh   /* Free temporary memory and return success */
5163ce4b0fdfSdrh   sqlite3StackFreeNN(pParse->db, pSpace);
5164a18f3d27Sdrh   return SQLITE_OK;
5165a18f3d27Sdrh }
516694a11211Sdrh 
516794a11211Sdrh /*
516860c96cd7Sdrh ** Most queries use only a single table (they are not joins) and have
516960c96cd7Sdrh ** simple == constraints against indexed fields.  This routine attempts
517060c96cd7Sdrh ** to plan those simple cases using much less ceremony than the
517160c96cd7Sdrh ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
517260c96cd7Sdrh ** times for the common case.
517360c96cd7Sdrh **
517460c96cd7Sdrh ** Return non-zero on success, if this query can be handled by this
517560c96cd7Sdrh ** no-frills query planner.  Return zero if this query needs the
517660c96cd7Sdrh ** general-purpose query planner.
517760c96cd7Sdrh */
whereShortCut(WhereLoopBuilder * pBuilder)5178b8a8e8a5Sdrh static int whereShortCut(WhereLoopBuilder *pBuilder){
517960c96cd7Sdrh   WhereInfo *pWInfo;
51807601294aSdrh   SrcItem *pItem;
518160c96cd7Sdrh   WhereClause *pWC;
518260c96cd7Sdrh   WhereTerm *pTerm;
518360c96cd7Sdrh   WhereLoop *pLoop;
518460c96cd7Sdrh   int iCur;
518592a121f4Sdrh   int j;
518660c96cd7Sdrh   Table *pTab;
518760c96cd7Sdrh   Index *pIdx;
518836db90d3Sdrh   WhereScan scan;
518960c96cd7Sdrh 
519060c96cd7Sdrh   pWInfo = pBuilder->pWInfo;
5191ce943bc8Sdrh   if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
519260c96cd7Sdrh   assert( pWInfo->pTabList->nSrc>=1 );
519360c96cd7Sdrh   pItem = pWInfo->pTabList->a;
519460c96cd7Sdrh   pTab = pItem->pTab;
519560c96cd7Sdrh   if( IsVirtual(pTab) ) return 0;
51968c44962aSdrh   if( pItem->fg.isIndexedBy || pItem->fg.notIndexed ){
51978c44962aSdrh     testcase( pItem->fg.isIndexedBy );
51988c44962aSdrh     testcase( pItem->fg.notIndexed );
51998c44962aSdrh     return 0;
52008c44962aSdrh   }
520160c96cd7Sdrh   iCur = pItem->iCursor;
520260c96cd7Sdrh   pWC = &pWInfo->sWC;
520360c96cd7Sdrh   pLoop = pBuilder->pNew;
520460c96cd7Sdrh   pLoop->wsFlags = 0;
5205c8bbce1eSdrh   pLoop->nSkip = 0;
520636db90d3Sdrh   pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0);
52073768f175Sdrh   while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
520860c96cd7Sdrh   if( pTerm ){
5209e8d0c61fSdrh     testcase( pTerm->eOperator & WO_IS );
521060c96cd7Sdrh     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
521160c96cd7Sdrh     pLoop->aLTerm[0] = pTerm;
521260c96cd7Sdrh     pLoop->nLTerm = 1;
521360c96cd7Sdrh     pLoop->u.btree.nEq = 1;
5214e1e2e9acSdrh     /* TUNING: Cost of a rowid lookup is 10 */
5215bf539c4dSdrh     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
521660c96cd7Sdrh   }else{
521760c96cd7Sdrh     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
52184e5bef8cSmistachkin       int opMask;
5219cd40abb2Sdan       assert( pLoop->aLTermSpace==pLoop->aLTerm );
52205f1d1d9cSdrh       if( !IsUniqueIndex(pIdx)
5221cd40abb2Sdan        || pIdx->pPartIdxWhere!=0
5222bbbdc83bSdrh        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
5223cd40abb2Sdan       ) continue;
52244e5bef8cSmistachkin       opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
5225bbbdc83bSdrh       for(j=0; j<pIdx->nKeyCol; j++){
522636db90d3Sdrh         pTerm = whereScanInit(&scan, pWC, iCur, j, opMask, pIdx);
522736db90d3Sdrh         while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
522860c96cd7Sdrh         if( pTerm==0 ) break;
5229e8d0c61fSdrh         testcase( pTerm->eOperator & WO_IS );
523060c96cd7Sdrh         pLoop->aLTerm[j] = pTerm;
523160c96cd7Sdrh       }
5232bbbdc83bSdrh       if( j!=pIdx->nKeyCol ) continue;
523392a121f4Sdrh       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
52341fe3ac73Sdrh       if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
523592a121f4Sdrh         pLoop->wsFlags |= WHERE_IDX_ONLY;
523692a121f4Sdrh       }
523760c96cd7Sdrh       pLoop->nLTerm = j;
523860c96cd7Sdrh       pLoop->u.btree.nEq = j;
523960c96cd7Sdrh       pLoop->u.btree.pIndex = pIdx;
5240e1e2e9acSdrh       /* TUNING: Cost of a unique index lookup is 15 */
5241bf539c4dSdrh       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
524260c96cd7Sdrh       break;
524360c96cd7Sdrh     }
524460c96cd7Sdrh   }
52453b75ffaaSdrh   if( pLoop->wsFlags ){
5246bf539c4dSdrh     pLoop->nOut = (LogEst)1;
52473b75ffaaSdrh     pWInfo->a[0].pWLoop = pLoop;
5248628dfe16Sdrh     assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
5249628dfe16Sdrh     pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
52503b75ffaaSdrh     pWInfo->a[0].iTabCur = iCur;
52513b75ffaaSdrh     pWInfo->nRowOut = 1;
5252ddba0c22Sdrh     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
52536457a353Sdrh     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
52546457a353Sdrh       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
52556457a353Sdrh     }
525636db90d3Sdrh     if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS;
52573b75ffaaSdrh #ifdef SQLITE_DEBUG
52583b75ffaaSdrh     pLoop->cId = '0';
52593b75ffaaSdrh #endif
526036db90d3Sdrh #ifdef WHERETRACE_ENABLED
526136db90d3Sdrh     if( sqlite3WhereTrace ){
526236db90d3Sdrh       sqlite3DebugPrintf("whereShortCut() used to compute solution\n");
526336db90d3Sdrh     }
526436db90d3Sdrh #endif
52653b75ffaaSdrh     return 1;
52663b75ffaaSdrh   }
52673b75ffaaSdrh   return 0;
526860c96cd7Sdrh }
526960c96cd7Sdrh 
527060c96cd7Sdrh /*
5271c456a76fSdan ** Helper function for exprIsDeterministic().
5272c456a76fSdan */
exprNodeIsDeterministic(Walker * pWalker,Expr * pExpr)5273c456a76fSdan static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
5274c456a76fSdan   if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
5275c456a76fSdan     pWalker->eCode = 0;
5276c456a76fSdan     return WRC_Abort;
5277c456a76fSdan   }
5278c456a76fSdan   return WRC_Continue;
5279c456a76fSdan }
5280c456a76fSdan 
5281c456a76fSdan /*
5282c456a76fSdan ** Return true if the expression contains no non-deterministic SQL
5283c456a76fSdan ** functions. Do not consider non-deterministic SQL functions that are
5284c456a76fSdan ** part of sub-select statements.
5285c456a76fSdan */
exprIsDeterministic(Expr * p)5286c456a76fSdan static int exprIsDeterministic(Expr *p){
5287c456a76fSdan   Walker w;
5288c456a76fSdan   memset(&w, 0, sizeof(w));
5289c456a76fSdan   w.eCode = 1;
5290c456a76fSdan   w.xExprCallback = exprNodeIsDeterministic;
52917e6f980bSdrh   w.xSelectCallback = sqlite3SelectWalkFail;
5292c456a76fSdan   sqlite3WalkExpr(&w, p);
5293c456a76fSdan   return w.eCode;
5294c456a76fSdan }
5295c456a76fSdan 
5296cea1951eSdrh 
5297cea1951eSdrh #ifdef WHERETRACE_ENABLED
5298cea1951eSdrh /*
5299cea1951eSdrh ** Display all WhereLoops in pWInfo
5300cea1951eSdrh */
showAllWhereLoops(WhereInfo * pWInfo,WhereClause * pWC)5301cea1951eSdrh static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
5302cea1951eSdrh   if( sqlite3WhereTrace ){    /* Display all of the WhereLoop objects */
5303cea1951eSdrh     WhereLoop *p;
5304cea1951eSdrh     int i;
5305cea1951eSdrh     static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
5306cea1951eSdrh                                            "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
5307cea1951eSdrh     for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
5308cea1951eSdrh       p->cId = zLabel[i%(sizeof(zLabel)-1)];
5309cea1951eSdrh       sqlite3WhereLoopPrint(p, pWC);
5310cea1951eSdrh     }
5311cea1951eSdrh   }
5312cea1951eSdrh }
5313cea1951eSdrh # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
5314cea1951eSdrh #else
5315cea1951eSdrh # define WHERETRACE_ALL_LOOPS(W,C)
5316cea1951eSdrh #endif
5317cea1951eSdrh 
531870b403b6Sdrh /* Attempt to omit tables from a join that do not affect the result.
531970b403b6Sdrh ** For a table to not affect the result, the following must be true:
532070b403b6Sdrh **
532170b403b6Sdrh **   1) The query must not be an aggregate.
532270b403b6Sdrh **   2) The table must be the RHS of a LEFT JOIN.
532370b403b6Sdrh **   3) Either the query must be DISTINCT, or else the ON or USING clause
532470b403b6Sdrh **      must contain a constraint that limits the scan of the table to
532570b403b6Sdrh **      at most a single row.
532670b403b6Sdrh **   4) The table must not be referenced by any part of the query apart
532770b403b6Sdrh **      from its own USING or ON clause.
532870b403b6Sdrh **
532970b403b6Sdrh ** For example, given:
533070b403b6Sdrh **
533170b403b6Sdrh **     CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
533270b403b6Sdrh **     CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
533370b403b6Sdrh **     CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
533470b403b6Sdrh **
533570b403b6Sdrh ** then table t2 can be omitted from the following:
533670b403b6Sdrh **
533770b403b6Sdrh **     SELECT v1, v3 FROM t1
533870b403b6Sdrh **       LEFT JOIN t2 ON (t1.ipk=t2.ipk)
533970b403b6Sdrh **       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
534070b403b6Sdrh **
534170b403b6Sdrh ** or from:
534270b403b6Sdrh **
534370b403b6Sdrh **     SELECT DISTINCT v1, v3 FROM t1
534470b403b6Sdrh **       LEFT JOIN t2
534570b403b6Sdrh **       LEFT JOIN t3 ON (t1.ipk=t3.ipk)
534670b403b6Sdrh */
whereOmitNoopJoin(WhereInfo * pWInfo,Bitmask notReady)534770b403b6Sdrh static SQLITE_NOINLINE Bitmask whereOmitNoopJoin(
534870b403b6Sdrh   WhereInfo *pWInfo,
534970b403b6Sdrh   Bitmask notReady
535070b403b6Sdrh ){
535170b403b6Sdrh   int i;
535270b403b6Sdrh   Bitmask tabUsed;
535370b403b6Sdrh 
535470b403b6Sdrh   /* Preconditions checked by the caller */
535570b403b6Sdrh   assert( pWInfo->nLevel>=2 );
535670b403b6Sdrh   assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );
535770b403b6Sdrh 
535870b403b6Sdrh   /* These two preconditions checked by the caller combine to guarantee
535970b403b6Sdrh   ** condition (1) of the header comment */
536070b403b6Sdrh   assert( pWInfo->pResultSet!=0 );
536170b403b6Sdrh   assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );
536270b403b6Sdrh 
536370b403b6Sdrh   tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
536470b403b6Sdrh   if( pWInfo->pOrderBy ){
536570b403b6Sdrh     tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
536670b403b6Sdrh   }
536770b403b6Sdrh   for(i=pWInfo->nLevel-1; i>=1; i--){
536870b403b6Sdrh     WhereTerm *pTerm, *pEnd;
536970b403b6Sdrh     SrcItem *pItem;
537070b403b6Sdrh     WhereLoop *pLoop;
537170b403b6Sdrh     pLoop = pWInfo->a[i].pWLoop;
537270b403b6Sdrh     pItem = &pWInfo->pTabList->a[pLoop->iTab];
53732a7aff93Sdan     if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;
537470b403b6Sdrh     if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0
537570b403b6Sdrh      && (pLoop->wsFlags & WHERE_ONEROW)==0
537670b403b6Sdrh     ){
537770b403b6Sdrh       continue;
537870b403b6Sdrh     }
537970b403b6Sdrh     if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
538070b403b6Sdrh     pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm;
538170b403b6Sdrh     for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
538270b403b6Sdrh       if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
538367a99dbeSdrh         if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
5384d1985262Sdrh          || pTerm->pExpr->w.iJoin!=pItem->iCursor
538570b403b6Sdrh         ){
538670b403b6Sdrh           break;
538770b403b6Sdrh         }
538870b403b6Sdrh       }
538970b403b6Sdrh     }
539070b403b6Sdrh     if( pTerm<pEnd ) continue;
539170b403b6Sdrh     WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
539270b403b6Sdrh     notReady &= ~pLoop->maskSelf;
539370b403b6Sdrh     for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
539470b403b6Sdrh       if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
539570b403b6Sdrh         pTerm->wtFlags |= TERM_CODED;
539670b403b6Sdrh       }
539770b403b6Sdrh     }
539870b403b6Sdrh     if( i!=pWInfo->nLevel-1 ){
539970b403b6Sdrh       int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
540070b403b6Sdrh       memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
540170b403b6Sdrh     }
540270b403b6Sdrh     pWInfo->nLevel--;
540370b403b6Sdrh     assert( pWInfo->nLevel>0 );
540470b403b6Sdrh   }
540570b403b6Sdrh   return notReady;
540670b403b6Sdrh }
540770b403b6Sdrh 
5408c456a76fSdan /*
5409fa35f5c5Sdrh ** Check to see if there are any SEARCH loops that might benefit from
5410fa35f5c5Sdrh ** using a Bloom filter.  Consider a Bloom filter if:
5411fa35f5c5Sdrh **
5412fa35f5c5Sdrh **   (1)  The SEARCH happens more than N times where N is the number
5413fa35f5c5Sdrh **        of rows in the table that is being considered for the Bloom
54147e910f64Sdrh **        filter.
54157e910f64Sdrh **   (2)  Some searches are expected to find zero rows.  (This is determined
54167e910f64Sdrh **        by the WHERE_SELFCULL flag on the term.)
54175a4ac1ccSdrh **   (3)  Bloom-filter processing is not disabled.  (Checked by the
54187e910f64Sdrh **        caller.)
54195a4ac1ccSdrh **   (4)  The size of the table being searched is known by ANALYZE.
5420fa35f5c5Sdrh **
5421fa35f5c5Sdrh ** This block of code merely checks to see if a Bloom filter would be
5422fa35f5c5Sdrh ** appropriate, and if so sets the WHERE_BLOOMFILTER flag on the
5423fa35f5c5Sdrh ** WhereLoop.  The implementation of the Bloom filter comes further
5424fa35f5c5Sdrh ** down where the code for each WhereLoop is generated.
5425fa35f5c5Sdrh */
whereCheckIfBloomFilterIsUseful(const WhereInfo * pWInfo)5426fa35f5c5Sdrh static SQLITE_NOINLINE void whereCheckIfBloomFilterIsUseful(
5427fecbf0a1Sdrh   const WhereInfo *pWInfo
5428fa35f5c5Sdrh ){
5429fa35f5c5Sdrh   int i;
5430fa35f5c5Sdrh   LogEst nSearch;
5431fa35f5c5Sdrh 
5432fa35f5c5Sdrh   assert( pWInfo->nLevel>=2 );
5433fecbf0a1Sdrh   assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) );
5434fa35f5c5Sdrh   nSearch = pWInfo->a[0].pWLoop->nOut;
5435fa35f5c5Sdrh   for(i=1; i<pWInfo->nLevel; i++){
5436fa35f5c5Sdrh     WhereLoop *pLoop = pWInfo->a[i].pWLoop;
5437b71a4853Sdrh     const unsigned int reqFlags = (WHERE_SELFCULL|WHERE_COLUMN_EQ);
5438fb82caf0Sdrh     if( (pLoop->wsFlags & reqFlags)==reqFlags
54395a4ac1ccSdrh      /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
5440a11c5e22Sdrh      && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
5441fb82caf0Sdrh     ){
5442fb82caf0Sdrh       SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab];
5443fb82caf0Sdrh       Table *pTab = pItem->pTab;
5444fb82caf0Sdrh       pTab->tabFlags |= TF_StatsUsed;
5445fb82caf0Sdrh       if( nSearch > pTab->nRowLogEst
54467e910f64Sdrh        && (pTab->tabFlags & TF_HasStat1)!=0
5447fa35f5c5Sdrh       ){
5448a11c5e22Sdrh         testcase( pItem->fg.jointype & JT_LEFT );
5449fa35f5c5Sdrh         pLoop->wsFlags |= WHERE_BLOOMFILTER;
5450fa35f5c5Sdrh         pLoop->wsFlags &= ~WHERE_IDX_ONLY;
5451fb82caf0Sdrh         WHERETRACE(0xffff, (
5452fb82caf0Sdrh            "-> use Bloom-filter on loop %c because there are ~%.1e "
5453fb82caf0Sdrh            "lookups into %s which has only ~%.1e rows\n",
5454fb82caf0Sdrh            pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
5455fb82caf0Sdrh            (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
5456fb82caf0Sdrh       }
5457fa35f5c5Sdrh     }
5458fa35f5c5Sdrh     nSearch += pLoop->nOut;
5459fa35f5c5Sdrh   }
5460fa35f5c5Sdrh }
5461fa35f5c5Sdrh 
5462fa35f5c5Sdrh /*
54634bc1cc18Sdrh ** This is an sqlite3ParserAddCleanup() callback that is invoked to
54644bc1cc18Sdrh ** free the Parse->pIdxExpr list when the Parse object is destroyed.
54654bc1cc18Sdrh */
whereIndexedExprCleanup(sqlite3 * db,void * pObject)5466e70d4583Sdrh static void whereIndexedExprCleanup(sqlite3 *db, void *pObject){
54674bc1cc18Sdrh   Parse *pParse = (Parse*)pObject;
54684bc1cc18Sdrh   while( pParse->pIdxExpr!=0 ){
5469e70d4583Sdrh     IndexedExpr *p = pParse->pIdxExpr;
54704bc1cc18Sdrh     pParse->pIdxExpr = p->pIENext;
54714bc1cc18Sdrh     sqlite3ExprDelete(db, p->pExpr);
54724bc1cc18Sdrh     sqlite3DbFreeNN(db, p);
54734bc1cc18Sdrh   }
54744bc1cc18Sdrh }
54754bc1cc18Sdrh 
54764bc1cc18Sdrh /*
54774bc1cc18Sdrh ** The index pIdx is used by a query and contains one or more expressions.
54784bc1cc18Sdrh ** In other words pIdx is an index on an expression.  iIdxCur is the cursor
54794bc1cc18Sdrh ** number for the index and iDataCur is the cursor number for the corresponding
54804bc1cc18Sdrh ** table.
54814bc1cc18Sdrh **
5482e70d4583Sdrh ** This routine adds IndexedExpr entries to the Parse->pIdxExpr field for
54834bc1cc18Sdrh ** each of the expressions in the index so that the expression code generator
54844bc1cc18Sdrh ** will know to replace occurrences of the indexed expression with
54854bc1cc18Sdrh ** references to the corresponding column of the index.
54864bc1cc18Sdrh */
whereAddIndexedExpr(Parse * pParse,Index * pIdx,int iIdxCur,SrcItem * pTabItem)5487e70d4583Sdrh static SQLITE_NOINLINE void whereAddIndexedExpr(
5488e70d4583Sdrh   Parse *pParse,     /* Add IndexedExpr entries to pParse->pIdxExpr */
54894bc1cc18Sdrh   Index *pIdx,       /* The index-on-expression that contains the expressions */
54904bc1cc18Sdrh   int iIdxCur,       /* Cursor number for pIdx */
54917a98937dSdrh   SrcItem *pTabItem  /* The FROM clause entry for the table */
54924bc1cc18Sdrh ){
54934bc1cc18Sdrh   int i;
5494e70d4583Sdrh   IndexedExpr *p;
549508535840Sdrh   Table *pTab;
549608535840Sdrh   assert( pIdx->bHasExpr );
549708535840Sdrh   pTab = pIdx->pTable;
54984bc1cc18Sdrh   for(i=0; i<pIdx->nColumn; i++){
549908535840Sdrh     Expr *pExpr;
550008535840Sdrh     int j = pIdx->aiColumn[i];
5501e1805640Sdrh     int bMaybeNullRow;
550208535840Sdrh     if( j==XN_EXPR ){
550308535840Sdrh       pExpr = pIdx->aColExpr->a[i].pExpr;
5504e1805640Sdrh       testcase( pTabItem->fg.jointype & JT_LEFT );
5505e1805640Sdrh       testcase( pTabItem->fg.jointype & JT_RIGHT );
5506e1805640Sdrh       testcase( pTabItem->fg.jointype & JT_LTORJ );
5507e1805640Sdrh       bMaybeNullRow = (pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0;
550808535840Sdrh     }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
550908535840Sdrh       pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
5510e1805640Sdrh       bMaybeNullRow = 0;
551108535840Sdrh     }else{
551208535840Sdrh       continue;
551308535840Sdrh     }
551472ab3661Sdrh     if( sqlite3ExprIsConstant(pExpr) ) continue;
5515e70d4583Sdrh     p = sqlite3DbMallocRaw(pParse->db,  sizeof(IndexedExpr));
55164bc1cc18Sdrh     if( p==0 ) break;
55174bc1cc18Sdrh     p->pIENext = pParse->pIdxExpr;
551808535840Sdrh     p->pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
55197a98937dSdrh     p->iDataCur = pTabItem->iCursor;
55204bc1cc18Sdrh     p->iIdxCur = iIdxCur;
55214bc1cc18Sdrh     p->iIdxCol = i;
5522e1805640Sdrh     p->bMaybeNullRow = bMaybeNullRow;
55237a2a8ceeSdrh #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
55247a2a8ceeSdrh     p->zIdxName = pIdx->zName;
55257a2a8ceeSdrh #endif
55264bc1cc18Sdrh     pParse->pIdxExpr = p;
55274bc1cc18Sdrh     if( p->pIENext==0 ){
5528e70d4583Sdrh       sqlite3ParserAddCleanup(pParse, whereIndexedExprCleanup, pParse);
55294bc1cc18Sdrh     }
55304bc1cc18Sdrh   }
55314bc1cc18Sdrh }
55324bc1cc18Sdrh 
55334bc1cc18Sdrh /*
5534e3184744Sdrh ** Generate the beginning of the loop used for WHERE clause processing.
5535acf3b988Sdrh ** The return value is a pointer to an opaque structure that contains
553675897234Sdrh ** information needed to terminate the loop.  Later, the calling routine
55374adee20fSdanielk1977 ** should invoke sqlite3WhereEnd() with the return value of this function
553875897234Sdrh ** in order to complete the WHERE clause processing.
553975897234Sdrh **
554075897234Sdrh ** If an error occurs, this routine returns NULL.
5541c27a1ce4Sdrh **
5542c27a1ce4Sdrh ** The basic idea is to do a nested loop, one loop for each table in
5543c27a1ce4Sdrh ** the FROM clause of a select.  (INSERT and UPDATE statements are the
5544c27a1ce4Sdrh ** same as a SELECT with only a single table in the FROM clause.)  For
5545c27a1ce4Sdrh ** example, if the SQL is this:
5546c27a1ce4Sdrh **
5547c27a1ce4Sdrh **       SELECT * FROM t1, t2, t3 WHERE ...;
5548c27a1ce4Sdrh **
5549c27a1ce4Sdrh ** Then the code generated is conceptually like the following:
5550c27a1ce4Sdrh **
5551c27a1ce4Sdrh **      foreach row1 in t1 do       \    Code generated
55524adee20fSdanielk1977 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
5553c27a1ce4Sdrh **          foreach row3 in t3 do   /
5554c27a1ce4Sdrh **            ...
5555c27a1ce4Sdrh **          end                     \    Code generated
55564adee20fSdanielk1977 **        end                        |-- by sqlite3WhereEnd()
5557c27a1ce4Sdrh **      end                         /
5558c27a1ce4Sdrh **
555929dda4aeSdrh ** Note that the loops might not be nested in the order in which they
556029dda4aeSdrh ** appear in the FROM clause if a different order is better able to make
556151147baaSdrh ** use of indices.  Note also that when the IN operator appears in
556251147baaSdrh ** the WHERE clause, it might result in additional nested loops for
556351147baaSdrh ** scanning through all values on the right-hand side of the IN.
556429dda4aeSdrh **
5565c27a1ce4Sdrh ** There are Btree cursors associated with each table.  t1 uses cursor
55666a3ea0e6Sdrh ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
55676a3ea0e6Sdrh ** And so forth.  This routine generates code to open those VDBE cursors
55684adee20fSdanielk1977 ** and sqlite3WhereEnd() generates the code to close them.
5569c27a1ce4Sdrh **
5570e6f85e71Sdrh ** The code that sqlite3WhereBegin() generates leaves the cursors named
5571e6f85e71Sdrh ** in pTabList pointing at their appropriate entries.  The [...] code
5572f0863fe5Sdrh ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
5573e6f85e71Sdrh ** data from the various tables of the loop.
5574e6f85e71Sdrh **
5575c27a1ce4Sdrh ** If the WHERE clause is empty, the foreach loops must each scan their
5576c27a1ce4Sdrh ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
5577c27a1ce4Sdrh ** the tables have indices and there are terms in the WHERE clause that
5578c27a1ce4Sdrh ** refer to those indices, a complete table scan can be avoided and the
5579c27a1ce4Sdrh ** code will run much faster.  Most of the work of this routine is checking
5580c27a1ce4Sdrh ** to see if there are indices that can be used to speed up the loop.
5581c27a1ce4Sdrh **
5582c27a1ce4Sdrh ** Terms of the WHERE clause are also used to limit which rows actually
5583c27a1ce4Sdrh ** make it to the "..." in the middle of the loop.  After each "foreach",
5584c27a1ce4Sdrh ** terms of the WHERE clause that use only terms in that loop and outer
5585c27a1ce4Sdrh ** loops are evaluated and if false a jump is made around all subsequent
5586c27a1ce4Sdrh ** inner loops (or around the "..." if the test occurs within the inner-
5587c27a1ce4Sdrh ** most loop)
5588c27a1ce4Sdrh **
5589c27a1ce4Sdrh ** OUTER JOINS
5590c27a1ce4Sdrh **
5591c27a1ce4Sdrh ** An outer join of tables t1 and t2 is conceptally coded as follows:
5592c27a1ce4Sdrh **
5593c27a1ce4Sdrh **    foreach row1 in t1 do
5594c27a1ce4Sdrh **      flag = 0
5595c27a1ce4Sdrh **      foreach row2 in t2 do
5596c27a1ce4Sdrh **        start:
5597c27a1ce4Sdrh **          ...
5598c27a1ce4Sdrh **          flag = 1
5599c27a1ce4Sdrh **      end
5600e3184744Sdrh **      if flag==0 then
5601e3184744Sdrh **        move the row2 cursor to a null row
5602e3184744Sdrh **        goto start
5603e3184744Sdrh **      fi
5604c27a1ce4Sdrh **    end
5605c27a1ce4Sdrh **
5606e3184744Sdrh ** ORDER BY CLAUSE PROCESSING
5607e3184744Sdrh **
56089443342eSdrh ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
56099443342eSdrh ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
5610e3184744Sdrh ** if there is one.  If there is no ORDER BY clause or if this routine
561146ec5b63Sdrh ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
5612fc8d4f96Sdrh **
5613fc8d4f96Sdrh ** The iIdxCur parameter is the cursor number of an index.  If
5614ce943bc8Sdrh ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
5615fc8d4f96Sdrh ** to use for OR clause processing.  The WHERE clause should use this
5616fc8d4f96Sdrh ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
5617fc8d4f96Sdrh ** the first cursor in an array of cursors for all indices.  iIdxCur should
5618fc8d4f96Sdrh ** be used to compute the appropriate cursor depending on which index is
5619fc8d4f96Sdrh ** used.
562075897234Sdrh */
sqlite3WhereBegin(Parse * pParse,SrcList * pTabList,Expr * pWhere,ExprList * pOrderBy,ExprList * pResultSet,Select * pSelect,u16 wctrlFlags,int iAuxArg)56214adee20fSdanielk1977 WhereInfo *sqlite3WhereBegin(
562275897234Sdrh   Parse *pParse,          /* The parser context */
56236457a353Sdrh   SrcList *pTabList,      /* FROM clause: A list of all tables to be scanned */
562475897234Sdrh   Expr *pWhere,           /* The WHERE clause */
56250401acecSdrh   ExprList *pOrderBy,     /* An ORDER BY (or GROUP BY) clause, or NULL */
5626e9ba910fSdrh   ExprList *pResultSet,   /* Query result set.  Req'd for DISTINCT */
5627f55a7dadSdrh   Select *pSelect,        /* The entire SELECT statement */
5628f1b5ff73Sdrh   u16 wctrlFlags,         /* The WHERE_* flags defined in sqliteInt.h */
5629ce943bc8Sdrh   int iAuxArg             /* If WHERE_OR_SUBCLAUSE is set, index cursor number
5630c3489bbfSdrh                           ** If WHERE_USE_LIMIT, then the limit amount */
563175897234Sdrh ){
5632be229650Sdanielk1977   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
5633c01a3c17Sdrh   int nTabList;              /* Number of elements in pTabList */
563475897234Sdrh   WhereInfo *pWInfo;         /* Will become the return value of this function */
563575897234Sdrh   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
5636fe05af87Sdrh   Bitmask notReady;          /* Cursors that are not yet positioned */
56371c8148ffSdrh   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
5638111a6a7dSdrh   WhereMaskSet *pMaskSet;    /* The expression mask set */
56394d85fa76Sdrh   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
5640fd636c75Sdrh   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
56419cd1c99fSdrh   int ii;                    /* Loop counter */
564217435752Sdrh   sqlite3 *db;               /* Database connection */
56435346e95dSdrh   int rc;                    /* Return code */
56449c0c57a4Sdrh   u8 bFordelete = 0;         /* OPFLAG_FORDELETE or zero, as appropriate */
564575897234Sdrh 
5646f0ee1d3cSdan   assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
5647f0ee1d3cSdan         (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
5648ce943bc8Sdrh      && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
5649f0ee1d3cSdan   ));
565056f1b99dSdrh 
5651ce943bc8Sdrh   /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
5652ce943bc8Sdrh   assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
5653c3489bbfSdrh             || (wctrlFlags & WHERE_USE_LIMIT)==0 );
5654c3489bbfSdrh 
565556f1b99dSdrh   /* Variable initialization */
5656fd636c75Sdrh   db = pParse->db;
56571c8148ffSdrh   memset(&sWLB, 0, sizeof(sWLB));
56580401acecSdrh 
56590401acecSdrh   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
56600401acecSdrh   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
56610401acecSdrh   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
566256f1b99dSdrh 
566329dda4aeSdrh   /* The number of tables in the FROM clause is limited by the number of
56641398ad36Sdrh   ** bits in a Bitmask
56651398ad36Sdrh   */
566667ae0cb2Sdrh   testcase( pTabList->nSrc==BMS );
566729dda4aeSdrh   if( pTabList->nSrc>BMS ){
566829dda4aeSdrh     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
56691398ad36Sdrh     return 0;
56701398ad36Sdrh   }
56711398ad36Sdrh 
5672c01a3c17Sdrh   /* This function normally generates a nested loop for all tables in
5673ce943bc8Sdrh   ** pTabList.  But if the WHERE_OR_SUBCLAUSE flag is set, then we should
5674c01a3c17Sdrh   ** only generate code for the first table in pTabList and assume that
5675c01a3c17Sdrh   ** any cursors associated with subsequent tables are uninitialized.
5676c01a3c17Sdrh   */
5677ce943bc8Sdrh   nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
5678c01a3c17Sdrh 
567975897234Sdrh   /* Allocate and initialize the WhereInfo structure that will become the
5680be229650Sdanielk1977   ** return value. A single allocation is used to store the WhereInfo
5681be229650Sdanielk1977   ** struct, the contents of WhereInfo.a[], the WhereClause structure
5682be229650Sdanielk1977   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
5683be229650Sdanielk1977   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
5684be229650Sdanielk1977   ** some architectures. Hence the ROUND8() below.
568575897234Sdrh   */
5686cf6e3fd7Sdrh   nByteWInfo = ROUND8P(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
568787c05f0cSdrh   pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
568817435752Sdrh   if( db->mallocFailed ){
56898b307fbfSdrh     sqlite3DbFree(db, pWInfo);
56908b307fbfSdrh     pWInfo = 0;
569185574e31Sdanielk1977     goto whereBeginError;
569275897234Sdrh   }
569375897234Sdrh   pWInfo->pParse = pParse;
569475897234Sdrh   pWInfo->pTabList = pTabList;
56956b7157bbSdrh   pWInfo->pOrderBy = pOrderBy;
569663b3a64cSdrh #if WHERETRACE_ENABLED
5697aca19e19Sdrh   pWInfo->pWhere = pWhere;
569863b3a64cSdrh #endif
56996457a353Sdrh   pWInfo->pResultSet = pResultSet;
570087c05f0cSdrh   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
570187c05f0cSdrh   pWInfo->nLevel = nTabList;
5702ec4ccdbcSdrh   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
57036df2acd2Sdrh   pWInfo->wctrlFlags = wctrlFlags;
5704c3489bbfSdrh   pWInfo->iLimit = iAuxArg;
57058b307fbfSdrh   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
5706f55a7dadSdrh   pWInfo->pSelect = pSelect;
570787c05f0cSdrh   memset(&pWInfo->nOBSat, 0,
570887c05f0cSdrh          offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
570987c05f0cSdrh   memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
5710b0264eecSdrh   assert( pWInfo->eOnePass==ONEPASS_OFF );  /* ONEPASS defaults to OFF */
571170d18344Sdrh   pMaskSet = &pWInfo->sMaskSet;
5712844a89b5Sdrh   pMaskSet->n = 0;
5713844a89b5Sdrh   pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be
5714844a89b5Sdrh                          ** a valid cursor number, to avoid an initial
5715844a89b5Sdrh                          ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
57161c8148ffSdrh   sWLB.pWInfo = pWInfo;
571770d18344Sdrh   sWLB.pWC = &pWInfo->sWC;
57181ac87e1eSdrh   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
57191ac87e1eSdrh   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
572060c96cd7Sdrh   whereLoopInit(sWLB.pNew);
5721b8a8e8a5Sdrh #ifdef SQLITE_DEBUG
5722b8a8e8a5Sdrh   sWLB.pNew->cId = '*';
5723b8a8e8a5Sdrh #endif
5724111a6a7dSdrh 
5725111a6a7dSdrh   /* Split the WHERE clause into separate subexpressions where each
5726111a6a7dSdrh   ** subexpression is separated by an AND operator.
5727111a6a7dSdrh   */
57286c1f4ef2Sdrh   sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
57296c1f4ef2Sdrh   sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
573008192d5fSdrh 
57314fe425adSdrh   /* Special case: No FROM clause
57324fe425adSdrh   */
57334fe425adSdrh   if( nTabList==0 ){
5734ddba0c22Sdrh     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
57359b3bfa00Sdrh     if( (wctrlFlags & WHERE_WANT_DISTINCT)!=0
57369b3bfa00Sdrh      && OptimizationEnabled(db, SQLITE_DistinctOpt)
57379b3bfa00Sdrh     ){
57386457a353Sdrh       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
57396457a353Sdrh     }
5740fa16f5d9Sdrh     ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
574183e8ca54Sdrh   }else{
574242165be1Sdrh     /* Assign a bit from the bitmask to every term in the FROM clause.
574342165be1Sdrh     **
574447991425Sdrh     ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
574547991425Sdrh     **
574647991425Sdrh     ** The rule of the previous sentence ensures thta if X is the bitmask for
574747991425Sdrh     ** a table T, then X-1 is the bitmask for all other tables to the left of T.
574847991425Sdrh     ** Knowing the bitmask for all tables to the left of a left join is
574947991425Sdrh     ** important.  Ticket #3015.
5750e672c8edSdanielk1977     **
5751c01a3c17Sdrh     ** Note that bitmasks are created for all pTabList->nSrc tables in
5752c01a3c17Sdrh     ** pTabList, not just the first nTabList tables.  nTabList is normally
5753c01a3c17Sdrh     ** equal to pTabList->nSrc but might be shortened to 1 if the
5754ce943bc8Sdrh     ** WHERE_OR_SUBCLAUSE flag is set.
575542165be1Sdrh     */
575683e8ca54Sdrh     ii = 0;
575783e8ca54Sdrh     do{
57589cd1c99fSdrh       createMask(pMaskSet, pTabList->a[ii].iCursor);
575901d230ceSdrh       sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
576083e8ca54Sdrh     }while( (++ii)<pTabList->nSrc );
576147991425Sdrh   #ifdef SQLITE_DEBUG
5762269ba804Sdrh     {
5763269ba804Sdrh       Bitmask mx = 0;
57649cd1c99fSdrh       for(ii=0; ii<pTabList->nSrc; ii++){
57656f82e85aSdrh         Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
5766269ba804Sdrh         assert( m>=mx );
5767269ba804Sdrh         mx = m;
5768269ba804Sdrh       }
576942165be1Sdrh     }
577042165be1Sdrh   #endif
577183e8ca54Sdrh   }
577242165be1Sdrh 
5773b121dd14Sdrh   /* Analyze all of the subexpressions. */
57746c1f4ef2Sdrh   sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
5775f55a7dadSdrh   if( pSelect && pSelect->pLimit ){
5776f55a7dadSdrh     sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
5777f55a7dadSdrh   }
5778a5ec23a7Sdan   if( pParse->nErr ) goto whereBeginError;
577975897234Sdrh 
5780c456a76fSdan   /* Special case: WHERE terms that do not refer to any tables in the join
5781c456a76fSdan   ** (constant expressions). Evaluate each such term, and jump over all the
5782c456a76fSdan   ** generated code if the result is not true.
5783c456a76fSdan   **
5784c456a76fSdan   ** Do not do this if the expression contains non-deterministic functions
5785c456a76fSdan   ** that are not within a sub-select. This is not strictly required, but
5786c456a76fSdan   ** preserves SQLite's legacy behaviour in the following two cases:
5787c456a76fSdan   **
5788c456a76fSdan   **   FROM ... WHERE random()>0;           -- eval random() once per row
5789c456a76fSdan   **   FROM ... WHERE (SELECT random())>0;  -- eval random() once overall
5790c456a76fSdan   */
5791132f96fcSdrh   for(ii=0; ii<sWLB.pWC->nBase; ii++){
5792c456a76fSdan     WhereTerm *pT = &sWLB.pWC->a[ii];
579333f10207Sdrh     if( pT->wtFlags & TERM_VIRTUAL ) continue;
5794c456a76fSdan     if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
5795c456a76fSdan       sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
5796c456a76fSdan       pT->wtFlags |= TERM_CODED;
5797c456a76fSdan     }
5798c456a76fSdan   }
5799c456a76fSdan 
58006457a353Sdrh   if( wctrlFlags & WHERE_WANT_DISTINCT ){
58019b3bfa00Sdrh     if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
58029b3bfa00Sdrh       /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
58039b3bfa00Sdrh       ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
58049b3bfa00Sdrh       wctrlFlags &= ~WHERE_WANT_DISTINCT;
58059b3bfa00Sdrh       pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT;
58069b3bfa00Sdrh     }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
58076457a353Sdrh       /* The DISTINCT marking is pointless.  Ignore it. */
580838cc40c2Sdan       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
58094f402f26Sdrh     }else if( pOrderBy==0 ){
58106457a353Sdrh       /* Try to ORDER BY the result set to make distinct processing easier */
58114f402f26Sdrh       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
58126457a353Sdrh       pWInfo->pOrderBy = pResultSet;
58134f402f26Sdrh     }
581438cc40c2Sdan   }
581538cc40c2Sdan 
5816f1b5f5b8Sdrh   /* Construct the WhereLoop objects */
5817c90713d3Sdrh #if defined(WHERETRACE_ENABLED)
5818c3489bbfSdrh   if( sqlite3WhereTrace & 0xffff ){
5819c3489bbfSdrh     sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
5820c3489bbfSdrh     if( wctrlFlags & WHERE_USE_LIMIT ){
5821c3489bbfSdrh       sqlite3DebugPrintf(", limit: %d", iAuxArg);
5822c3489bbfSdrh     }
5823c3489bbfSdrh     sqlite3DebugPrintf(")\n");
582455b4c827Sdrh     if( sqlite3WhereTrace & 0x100 ){
582555b4c827Sdrh       Select sSelect;
582655b4c827Sdrh       memset(&sSelect, 0, sizeof(sSelect));
582755b4c827Sdrh       sSelect.selFlags = SF_WhereBegin;
582855b4c827Sdrh       sSelect.pSrc = pTabList;
582955b4c827Sdrh       sSelect.pWhere = pWhere;
583055b4c827Sdrh       sSelect.pOrderBy = pOrderBy;
583155b4c827Sdrh       sSelect.pEList = pResultSet;
583255b4c827Sdrh       sqlite3TreeViewSelect(0, &sSelect, 0);
583355b4c827Sdrh     }
5834c3489bbfSdrh   }
5835b121dd14Sdrh   if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
583605fbfd82Sdrh     sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
5837c84a4020Sdrh     sqlite3WhereClausePrint(sWLB.pWC);
5838c90713d3Sdrh   }
5839c90713d3Sdrh #endif
5840c90713d3Sdrh 
5841b8a8e8a5Sdrh   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
58425346e95dSdrh     rc = whereLoopAddAll(&sWLB);
58435346e95dSdrh     if( rc ) goto whereBeginError;
5844f1b5f5b8Sdrh 
584589efac94Sdrh #ifdef SQLITE_ENABLE_STAT4
584689efac94Sdrh     /* If one or more WhereTerm.truthProb values were used in estimating
584789efac94Sdrh     ** loop parameters, but then those truthProb values were subsequently
584889efac94Sdrh     ** changed based on STAT4 information while computing subsequent loops,
584989efac94Sdrh     ** then we need to rerun the whole loop building process so that all
585089efac94Sdrh     ** loops will be built using the revised truthProb values. */
585189efac94Sdrh     if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
5852cea1951eSdrh       WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
585389efac94Sdrh       WHERETRACE(0xffff,
5854f06cdde2Sdrh            ("**** Redo all loop computations due to"
5855f06cdde2Sdrh             " TERM_HIGHTRUTH changes ****\n"));
585689efac94Sdrh       while( pWInfo->pLoops ){
585789efac94Sdrh         WhereLoop *p = pWInfo->pLoops;
585889efac94Sdrh         pWInfo->pLoops = p->pNextLoop;
585989efac94Sdrh         whereLoopDelete(db, p);
586089efac94Sdrh       }
586189efac94Sdrh       rc = whereLoopAddAll(&sWLB);
586289efac94Sdrh       if( rc ) goto whereBeginError;
586389efac94Sdrh     }
586489efac94Sdrh #endif
5865cea1951eSdrh     WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
5866a18f3d27Sdrh 
58674f402f26Sdrh     wherePathSolver(pWInfo, 0);
5868a18f3d27Sdrh     if( db->mallocFailed ) goto whereBeginError;
5869a50ef114Sdrh     if( pWInfo->pOrderBy ){
5870c7f0d229Sdrh        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
5871a50ef114Sdrh        if( db->mallocFailed ) goto whereBeginError;
587260c96cd7Sdrh     }
587360c96cd7Sdrh   }
587460c96cd7Sdrh   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
58758426e36cSdrh      pWInfo->revMask = ALLBITS;
5876a50ef114Sdrh   }
58770c7d3d39Sdrh   if( pParse->nErr ){
587875b93405Sdrh     goto whereBeginError;
587975b93405Sdrh   }
58800c7d3d39Sdrh   assert( db->mallocFailed==0 );
5881b121dd14Sdrh #ifdef WHERETRACE_ENABLED
5882a18f3d27Sdrh   if( sqlite3WhereTrace ){
58834f402f26Sdrh     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
5884ddba0c22Sdrh     if( pWInfo->nOBSat>0 ){
5885ddba0c22Sdrh       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
5886319f677dSdrh     }
58874f402f26Sdrh     switch( pWInfo->eDistinct ){
58884f402f26Sdrh       case WHERE_DISTINCT_UNIQUE: {
58894f402f26Sdrh         sqlite3DebugPrintf("  DISTINCT=unique");
58904f402f26Sdrh         break;
58914f402f26Sdrh       }
58924f402f26Sdrh       case WHERE_DISTINCT_ORDERED: {
58934f402f26Sdrh         sqlite3DebugPrintf("  DISTINCT=ordered");
58944f402f26Sdrh         break;
58954f402f26Sdrh       }
58964f402f26Sdrh       case WHERE_DISTINCT_UNORDERED: {
58974f402f26Sdrh         sqlite3DebugPrintf("  DISTINCT=unordered");
58984f402f26Sdrh         break;
58994f402f26Sdrh       }
59004f402f26Sdrh     }
59014f402f26Sdrh     sqlite3DebugPrintf("\n");
5902fd636c75Sdrh     for(ii=0; ii<pWInfo->nLevel; ii++){
5903cacdf207Sdrh       sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
5904f1b5f5b8Sdrh     }
5905f1b5f5b8Sdrh   }
5906f1b5f5b8Sdrh #endif
590741203c6cSdan 
590870b403b6Sdrh   /* Attempt to omit tables from a join that do not affect the result.
590970b403b6Sdrh   ** See the comment on whereOmitNoopJoin() for further information.
591041203c6cSdan   **
591170b403b6Sdrh   ** This query optimization is factored out into a separate "no-inline"
591270b403b6Sdrh   ** procedure to keep the sqlite3WhereBegin() procedure from becoming
591370b403b6Sdrh   ** too large.  If sqlite3WhereBegin() becomes too large, that prevents
591470b403b6Sdrh   ** some C-compiler optimizers from in-lining the
591570b403b6Sdrh   ** sqlite3WhereCodeOneLoopStart() procedure, and it is important to
591670b403b6Sdrh   ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
591741203c6cSdan   */
591853bf7175Sdrh   notReady = ~(Bitmask)0;
59191031bd99Sdrh   if( pWInfo->nLevel>=2
5920f330d53fSdan    && pResultSet!=0                         /* these two combine to guarantee */
5921f330d53fSdan    && 0==(wctrlFlags & WHERE_AGG_DISTINCT)  /* condition (1) above */
59221031bd99Sdrh    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
59231031bd99Sdrh   ){
592470b403b6Sdrh     notReady = whereOmitNoopJoin(pWInfo, notReady);
592570b403b6Sdrh     nTabList = pWInfo->nLevel;
592670b403b6Sdrh     assert( nTabList>0 );
59276c1f4ef2Sdrh   }
592870b403b6Sdrh 
5929fa35f5c5Sdrh   /* Check to see if there are any SEARCH loops that might benefit from
5930fa35f5c5Sdrh   ** using a Bloom filter.
5931fa35f5c5Sdrh   */
5932fa35f5c5Sdrh   if( pWInfo->nLevel>=2
5933fa35f5c5Sdrh    && OptimizationEnabled(db, SQLITE_BloomFilter)
5934fa35f5c5Sdrh   ){
5935fecbf0a1Sdrh     whereCheckIfBloomFilterIsUseful(pWInfo);
5936fa35f5c5Sdrh   }
5937fa35f5c5Sdrh 
593805fbfd82Sdrh #if defined(WHERETRACE_ENABLED)
593905fbfd82Sdrh   if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
594005fbfd82Sdrh     sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
594105fbfd82Sdrh     sqlite3WhereClausePrint(sWLB.pWC);
594205fbfd82Sdrh   }
59433b48e8c9Sdrh   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
594405fbfd82Sdrh #endif
59458e23daf3Sdrh   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
5946f1b5f5b8Sdrh 
594708c88eb0Sdrh   /* If the caller is an UPDATE or DELETE statement that is requesting
594808c88eb0Sdrh   ** to use a one-pass algorithm, determine if this is appropriate.
59490c2ba13eSdan   **
59500c2ba13eSdan   ** A one-pass approach can be used if the caller has requested one
59510c2ba13eSdan   ** and either (a) the scan visits at most one row or (b) each
59520c2ba13eSdan   ** of the following are true:
59530c2ba13eSdan   **
59540c2ba13eSdan   **   * the caller has indicated that a one-pass approach can be used
59550c2ba13eSdan   **     with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
59560c2ba13eSdan   **   * the table is not a virtual table, and
59570c2ba13eSdan   **   * either the scan does not use the OR optimization or the caller
59580c2ba13eSdan   **     is a DELETE operation (WHERE_DUPLICATES_OK is only specified
59590c2ba13eSdan   **     for DELETE).
59600c2ba13eSdan   **
59610c2ba13eSdan   ** The last qualification is because an UPDATE statement uses
59620c2ba13eSdan   ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
59630c2ba13eSdan   ** use a one-pass approach, and this is not set accurately for scans
59640c2ba13eSdan   ** that use the OR optimization.
596508c88eb0Sdrh   */
5966165be38bSdrh   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
5967f0ee1d3cSdan   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
5968f0ee1d3cSdan     int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
5969f0ee1d3cSdan     int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
597058ed3743Sdan     assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
59710c2ba13eSdan     if( bOnerow || (
59720c2ba13eSdan         0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
597358ed3743Sdan      && !IsVirtual(pTabList->a[0].pTab)
59740c2ba13eSdan      && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
59750c2ba13eSdan     )){
5976b0264eecSdrh       pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
5977fd261ec6Sdan       if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
5978fd261ec6Sdan         if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
5979fd261ec6Sdan           bFordelete = OPFLAG_FORDELETE;
5980fd261ec6Sdan         }
5981fd261ec6Sdan         pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
598208c88eb0Sdrh       }
5983702ba9f2Sdrh     }
5984f0ee1d3cSdan   }
5985eb04de32Sdrh 
59869012bcbcSdrh   /* Open all tables in the pTabList and any indices selected for
59879012bcbcSdrh   ** searching those tables.
598875897234Sdrh   */
59899cd1c99fSdrh   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
5990da184236Sdanielk1977     Table *pTab;     /* Table to open */
5991da184236Sdanielk1977     int iDb;         /* Index of database containing table/index */
59927601294aSdrh     SrcItem *pTabItem;
5993f57b3399Sdrh 
599429dda4aeSdrh     pTabItem = &pTabList->a[pLevel->iFrom];
59959012bcbcSdrh     pTab = pTabItem->pTab;
5996595a523aSdanielk1977     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59977ba39a92Sdrh     pLoop = pLevel->pWLoop;
5998f38524d2Sdrh     if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){
599975bb9f5aSdrh       /* Do nothing */
600075bb9f5aSdrh     }else
60019eff6167Sdrh #ifndef SQLITE_OMIT_VIRTUALTABLE
60027ba39a92Sdrh     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
6003595a523aSdanielk1977       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
600493626f48Sdanielk1977       int iCur = pTabItem->iCursor;
6005595a523aSdanielk1977       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
6006fc5e5466Sdrh     }else if( IsVirtual(pTab) ){
6007fc5e5466Sdrh       /* noop */
60089eff6167Sdrh     }else
60099eff6167Sdrh #endif
6010a20c71e9Sdrh     if( ((pLoop->wsFlags & WHERE_IDX_ONLY)==0
6011a20c71e9Sdrh          && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0)
6012a20c71e9Sdrh      || (pTabItem->fg.jointype & (JT_LTORJ|JT_RIGHT))!=0
6013a20c71e9Sdrh     ){
6014fc8d4f96Sdrh       int op = OP_OpenRead;
6015b0264eecSdrh       if( pWInfo->eOnePass!=ONEPASS_OFF ){
6016fc8d4f96Sdrh         op = OP_OpenWrite;
6017fc8d4f96Sdrh         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
6018fc8d4f96Sdrh       };
601908c88eb0Sdrh       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
6020fc8d4f96Sdrh       assert( pTabItem->iCursor==pLevel->iTabCur );
6021b0264eecSdrh       testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
6022b0264eecSdrh       testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
60231a9082f6Sdrh       if( pWInfo->eOnePass==ONEPASS_OFF
60241a9082f6Sdrh        && pTab->nCol<BMS
60251a9082f6Sdrh        && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
602687fb37efSdrh        && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0
60271a9082f6Sdrh       ){
60281a9082f6Sdrh         /* If we know that only a prefix of the record will be used,
60291a9082f6Sdrh         ** it is advantageous to reduce the "column count" field in
60301a9082f6Sdrh         ** the P4 operand of the OP_OpenRead/Write opcode. */
60319792eeffSdanielk1977         Bitmask b = pTabItem->colUsed;
60329792eeffSdanielk1977         int n = 0;
603374161705Sdrh         for(; b; b=b>>1, n++){}
603400dcecabSdrh         sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
60359792eeffSdanielk1977         assert( n<=pTab->nCol );
60369792eeffSdanielk1977       }
6037ba25c7e2Sdrh #ifdef SQLITE_ENABLE_CURSOR_HINTS
6038c5dc3dcdSdan       if( pLoop->u.btree.pIndex!=0 ){
6039c5dc3dcdSdan         sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
6040c5dc3dcdSdan       }else
60412f2b0278Sdrh #endif
6042c5dc3dcdSdan       {
6043c5dc3dcdSdan         sqlite3VdbeChangeP5(v, bFordelete);
6044c5dc3dcdSdan       }
604597bae794Sdrh #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
604697bae794Sdrh       sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
604797bae794Sdrh                             (const u8*)&pTabItem->colUsed, P4_INT64);
604897bae794Sdrh #endif
6049c00da105Sdanielk1977     }else{
6050c00da105Sdanielk1977       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
60519012bcbcSdrh     }
60527e47cb8bSdrh     if( pLoop->wsFlags & WHERE_INDEXED ){
60537ba39a92Sdrh       Index *pIx = pLoop->u.btree.pIndex;
6054fc8d4f96Sdrh       int iIndexCur;
6055fc8d4f96Sdrh       int op = OP_OpenRead;
6056154896e8Sdrh       /* iAuxArg is always set to a positive value if ONEPASS is possible */
6057c3489bbfSdrh       assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
605848dd1d8eSdrh       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
6059ce943bc8Sdrh        && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
6060a3bc66a3Sdrh       ){
6061a3bc66a3Sdrh         /* This is one term of an OR-optimization using the PRIMARY KEY of a
6062a3bc66a3Sdrh         ** WITHOUT ROWID table.  No need for a separate index */
6063a3bc66a3Sdrh         iIndexCur = pLevel->iTabCur;
6064a3bc66a3Sdrh         op = 0;
6065b0264eecSdrh       }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
6066fc8d4f96Sdrh         Index *pJ = pTabItem->pTab->pIndex;
6067c3489bbfSdrh         iIndexCur = iAuxArg;
6068fc8d4f96Sdrh         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
6069fc8d4f96Sdrh         while( ALWAYS(pJ) && pJ!=pIx ){
6070fc8d4f96Sdrh           iIndexCur++;
6071fc8d4f96Sdrh           pJ = pJ->pNext;
6072fc8d4f96Sdrh         }
6073fc8d4f96Sdrh         op = OP_OpenWrite;
6074fc8d4f96Sdrh         pWInfo->aiCurOnePass[1] = iIndexCur;
6075ce943bc8Sdrh       }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
6076c3489bbfSdrh         iIndexCur = iAuxArg;
6077a72a15e4Sdrh         op = OP_ReopenIdx;
6078fc8d4f96Sdrh       }else{
6079fc8d4f96Sdrh         iIndexCur = pParse->nTab++;
6080c046f6d4Sdrh         if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){
6081e70d4583Sdrh           whereAddIndexedExpr(pParse, pIx, iIndexCur, pTabItem);
60824bc1cc18Sdrh         }
6083fc8d4f96Sdrh       }
6084fc8d4f96Sdrh       pLevel->iIdxCur = iIndexCur;
608540822eb2Sdrh       assert( pIx!=0 );
6086da184236Sdanielk1977       assert( pIx->pSchema==pTab->pSchema );
6087b0367fb8Sdrh       assert( iIndexCur>=0 );
6088a3bc66a3Sdrh       if( op ){
6089fc8d4f96Sdrh         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
60902ec2fb22Sdrh         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6091e0997b34Sdrh         if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
6092e0997b34Sdrh          && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
609315750a26Sdan          && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
609468cf0aceSdrh          && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
6095e0997b34Sdrh          && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
60968489bf5aSdrh          && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
6097e0997b34Sdrh         ){
6098576d0a9fSdrh           sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
6099e0997b34Sdrh         }
6100207872a4Sdanielk1977         VdbeComment((v, "%s", pIx->zName));
610197bae794Sdrh #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
610297bae794Sdrh         {
610397bae794Sdrh           u64 colUsed = 0;
610497bae794Sdrh           int ii, jj;
610597bae794Sdrh           for(ii=0; ii<pIx->nColumn; ii++){
610697bae794Sdrh             jj = pIx->aiColumn[ii];
610797bae794Sdrh             if( jj<0 ) continue;
610897bae794Sdrh             if( jj>63 ) jj = 63;
610997bae794Sdrh             if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
611097bae794Sdrh             colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
611197bae794Sdrh           }
611297bae794Sdrh           sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
611397bae794Sdrh                                 (u8*)&colUsed, P4_INT64);
611497bae794Sdrh         }
611597bae794Sdrh #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
611675897234Sdrh       }
6117a3bc66a3Sdrh     }
6118aceb31b1Sdrh     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
61197c1734b0Sdrh     if( (pTabItem->fg.jointype & JT_RIGHT)!=0
61207c1734b0Sdrh      && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
61217c1734b0Sdrh     ){
61227c1734b0Sdrh       WhereRightJoin *pRJ = pLevel->pRJ;
61237c1734b0Sdrh       pRJ->iMatch = pParse->nTab++;
61247c1734b0Sdrh       pRJ->regBloom = ++pParse->nMem;
61257c1734b0Sdrh       sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
61267c1734b0Sdrh       pRJ->regReturn = ++pParse->nMem;
61272bd9f44aSdrh       sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
6128c2308ad2Sdrh       assert( pTab==pTabItem->pTab );
6129c2308ad2Sdrh       if( HasRowid(pTab) ){
6130c2308ad2Sdrh         KeyInfo *pInfo;
61317c1734b0Sdrh         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
6132c2308ad2Sdrh         pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
6133c2308ad2Sdrh         if( pInfo ){
6134c2308ad2Sdrh           pInfo->aColl[0] = 0;
6135c2308ad2Sdrh           pInfo->aSortFlags[0] = 0;
6136c2308ad2Sdrh           sqlite3VdbeAppendP4(v, pInfo, P4_KEYINFO);
6137c2308ad2Sdrh         }
6138c2308ad2Sdrh       }else{
6139c2308ad2Sdrh         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
61407c1734b0Sdrh         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
6141c2308ad2Sdrh         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
6142c2308ad2Sdrh       }
6143e21e36ddSdrh       pLoop->wsFlags &= ~WHERE_IDX_ONLY;
614412c35ec3Sdrh       /* The nature of RIGHT JOIN processing is such that it messes up
614512c35ec3Sdrh       ** the output order.  So omit any ORDER BY/GROUP BY elimination
614612c35ec3Sdrh       ** optimizations.  We need to do an actual sort for RIGHT JOIN. */
614712c35ec3Sdrh       pWInfo->nOBSat = 0;
614812c35ec3Sdrh       pWInfo->eDistinct = WHERE_DISTINCT_UNORDERED;
6149a76ac88aSdrh     }
61509012bcbcSdrh   }
61519012bcbcSdrh   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
6152a21a64ddSdrh   if( db->mallocFailed ) goto whereBeginError;
615375897234Sdrh 
615429dda4aeSdrh   /* Generate the code to do the search.  Each iteration of the for
615529dda4aeSdrh   ** loop below generates code for a single nested loop of the VM
615629dda4aeSdrh   ** program.
615775897234Sdrh   */
61589cd1c99fSdrh   for(ii=0; ii<nTabList; ii++){
61596f9702edSdan     int addrExplain;
61606f9702edSdan     int wsFlags;
616140822eb2Sdrh     SrcItem *pSrc;
61626d64b4a0Sdrh     if( pParse->nErr ) goto whereBeginError;
61639cd1c99fSdrh     pLevel = &pWInfo->a[ii];
61646f9702edSdan     wsFlags = pLevel->pWLoop->wsFlags;
616540822eb2Sdrh     pSrc = &pTabList->a[pLevel->iFrom];
616640822eb2Sdrh     if( pSrc->fg.isMaterialized ){
616740822eb2Sdrh       if( pSrc->fg.isCorrelated ){
616840822eb2Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
616940822eb2Sdrh       }else{
6170361e0edeSdrh         int iOnce = sqlite3VdbeAddOp0(v, OP_Once);  VdbeCoverage(v);
617140822eb2Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
617240822eb2Sdrh         sqlite3VdbeJumpHere(v, iOnce);
617340822eb2Sdrh       }
617440822eb2Sdrh     }
6175fa35f5c5Sdrh     if( (wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))!=0 ){
6176fa35f5c5Sdrh       if( (wsFlags & WHERE_AUTO_INDEX)!=0 ){
6177cc04afdaSdrh #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
6178cc04afdaSdrh         constructAutomaticIndex(pParse, &pWInfo->sWC,
6179cc04afdaSdrh                   &pTabList->a[pLevel->iFrom], notReady, pLevel);
6180fa35f5c5Sdrh #endif
6181fa35f5c5Sdrh       }else{
618227a9e1f6Sdrh         sqlite3ConstructBloomFilter(pWInfo, ii, pLevel, notReady);
6183fa35f5c5Sdrh       }
6184cc04afdaSdrh       if( db->mallocFailed ) goto whereBeginError;
6185cc04afdaSdrh     }
61866f82e85aSdrh     addrExplain = sqlite3WhereExplainOneScan(
6187e2188f0bSdrh         pParse, pTabList, pLevel, wctrlFlags
61886f9702edSdan     );
6189cc04afdaSdrh     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
619047df8a2cSdrh     notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
61914a07e3dbSdan     pWInfo->iContinue = pLevel->addrCont;
6192ce943bc8Sdrh     if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
61936f82e85aSdrh       sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
61946f9702edSdan     }
6195ad2d8307Sdrh   }
61967ec764a2Sdrh 
61976fa978daSdrh   /* Done. */
61986bc69a2dSdrh   VdbeModuleComment((v, "Begin WHERE-core"));
61995e6d90feSdrh   pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
620075897234Sdrh   return pWInfo;
6201e23399fcSdrh 
6202e23399fcSdrh   /* Jump here if malloc fails */
620385574e31Sdanielk1977 whereBeginError:
62048b307fbfSdrh   if( pWInfo ){
62058b307fbfSdrh     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
620610fe840eSdrh     whereInfoFree(db, pWInfo);
62078b307fbfSdrh   }
6208e23399fcSdrh   return 0;
620975897234Sdrh }
621075897234Sdrh 
621175897234Sdrh /*
6212299bf7c2Sdrh ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
6213299bf7c2Sdrh ** index rather than the main table.  In SQLITE_DEBUG mode, we want
6214299bf7c2Sdrh ** to trace those changes if PRAGMA vdbe_addoptrace=on.  This routine
6215299bf7c2Sdrh ** does that.
6216299bf7c2Sdrh */
6217299bf7c2Sdrh #ifndef SQLITE_DEBUG
6218299bf7c2Sdrh # define OpcodeRewriteTrace(D,K,P) /* no-op */
6219299bf7c2Sdrh #else
6220299bf7c2Sdrh # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
sqlite3WhereOpcodeRewriteTrace(sqlite3 * db,int pc,VdbeOp * pOp)6221299bf7c2Sdrh   static void sqlite3WhereOpcodeRewriteTrace(
6222299bf7c2Sdrh     sqlite3 *db,
6223299bf7c2Sdrh     int pc,
6224299bf7c2Sdrh     VdbeOp *pOp
6225299bf7c2Sdrh   ){
6226299bf7c2Sdrh     if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
6227299bf7c2Sdrh     sqlite3VdbePrintOp(0, pc, pOp);
6228299bf7c2Sdrh   }
6229299bf7c2Sdrh #endif
6230299bf7c2Sdrh 
623175c493f7Sdrh #ifdef SQLITE_DEBUG
623275c493f7Sdrh /*
623375c493f7Sdrh ** Return true if cursor iCur is opened by instruction k of the
623475c493f7Sdrh ** bytecode.  Used inside of assert() only.
623575c493f7Sdrh */
cursorIsOpen(Vdbe * v,int iCur,int k)623675c493f7Sdrh static int cursorIsOpen(Vdbe *v, int iCur, int k){
623775c493f7Sdrh   while( k>=0 ){
623875c493f7Sdrh     VdbeOp *pOp = sqlite3VdbeGetOp(v,k--);
623975c493f7Sdrh     if( pOp->p1!=iCur ) continue;
624075c493f7Sdrh     if( pOp->opcode==OP_Close ) return 0;
624175c493f7Sdrh     if( pOp->opcode==OP_OpenRead ) return 1;
624275c493f7Sdrh     if( pOp->opcode==OP_OpenWrite ) return 1;
624375c493f7Sdrh     if( pOp->opcode==OP_OpenDup ) return 1;
624475c493f7Sdrh     if( pOp->opcode==OP_OpenAutoindex ) return 1;
624575c493f7Sdrh     if( pOp->opcode==OP_OpenEphemeral ) return 1;
624675c493f7Sdrh   }
624775c493f7Sdrh   return 0;
624875c493f7Sdrh }
624975c493f7Sdrh #endif /* SQLITE_DEBUG */
625075c493f7Sdrh 
6251299bf7c2Sdrh /*
6252c27a1ce4Sdrh ** Generate the end of the WHERE loop.  See comments on
62534adee20fSdanielk1977 ** sqlite3WhereBegin() for additional information.
625475897234Sdrh */
sqlite3WhereEnd(WhereInfo * pWInfo)62554adee20fSdanielk1977 void sqlite3WhereEnd(WhereInfo *pWInfo){
6256633e6d57Sdrh   Parse *pParse = pWInfo->pParse;
6257633e6d57Sdrh   Vdbe *v = pParse->pVdbe;
625819a775c2Sdrh   int i;
62596b56344dSdrh   WhereLevel *pLevel;
62607ba39a92Sdrh   WhereLoop *pLoop;
6261ad3cab52Sdrh   SrcList *pTabList = pWInfo->pTabList;
6262633e6d57Sdrh   sqlite3 *db = pParse->db;
6263f8556d01Sdrh   int iEnd = sqlite3VdbeCurrentAddr(v);
6264a5d06a3dSdrh   int nRJ = 0;
626519a775c2Sdrh 
62669012bcbcSdrh   /* Generate loop termination code.
62679012bcbcSdrh   */
62686bc69a2dSdrh   VdbeModuleComment((v, "End WHERE-core"));
6269c01a3c17Sdrh   for(i=pWInfo->nLevel-1; i>=0; i--){
6270cd8629e4Sdrh     int addr;
62716b56344dSdrh     pLevel = &pWInfo->a[i];
62727c1734b0Sdrh     if( pLevel->pRJ ){
627386c1beb4Sdrh       /* Terminate the subroutine that forms the interior of the loop of
627486c1beb4Sdrh       ** the RIGHT JOIN table */
627586c1beb4Sdrh       WhereRightJoin *pRJ = pLevel->pRJ;
62766134b2dfSdrh       sqlite3VdbeResolveLabel(v, pLevel->addrCont);
62776134b2dfSdrh       pLevel->addrCont = 0;
6278b77c3129Sdrh       pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v);
62792bd9f44aSdrh       sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1);
62802bd9f44aSdrh       VdbeCoverage(v);
6281a5d06a3dSdrh       nRJ++;
62827c1734b0Sdrh     }
62837ba39a92Sdrh     pLoop = pLevel->pWLoop;
62846b56344dSdrh     if( pLevel->op!=OP_Noop ){
62858489bf5aSdrh #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6286c04ea80fSdrh       int addrSeek = 0;
6287839fa6d8Sdrh       Index *pIdx;
6288172806e4Sdrh       int n;
62898489bf5aSdrh       if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
6290fa337cc1Sdrh        && i==pWInfo->nLevel-1  /* Ticket [ef9318757b152e3] 2017-10-21 */
62918489bf5aSdrh        && (pLoop->wsFlags & WHERE_INDEXED)!=0
6292839fa6d8Sdrh        && (pIdx = pLoop->u.btree.pIndex)->hasStat1
6293a79a0e73Sdan        && (n = pLoop->u.btree.nDistinctCol)>0
6294a2e2d92bSdrh        && pIdx->aiRowLogEst[n]>=36
62958489bf5aSdrh       ){
6296172806e4Sdrh         int r1 = pParse->nMem+1;
6297172806e4Sdrh         int j, op;
62988489bf5aSdrh         for(j=0; j<n; j++){
62998489bf5aSdrh           sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
63008489bf5aSdrh         }
6301172806e4Sdrh         pParse->nMem += n+1;
63028489bf5aSdrh         op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
6303c04ea80fSdrh         addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
63048489bf5aSdrh         VdbeCoverageIf(v, op==OP_SeekLT);
63058489bf5aSdrh         VdbeCoverageIf(v, op==OP_SeekGT);
63068489bf5aSdrh         sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
6307c04ea80fSdrh       }
63088489bf5aSdrh #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
63098489bf5aSdrh       /* The common case: Advance to the next row */
63106134b2dfSdrh       if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont);
6311e39a732cSdrh       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
6312d1d38488Sdrh       sqlite3VdbeChangeP5(v, pLevel->p5);
6313688852abSdrh       VdbeCoverage(v);
63147d176105Sdrh       VdbeCoverageIf(v, pLevel->op==OP_Next);
63157d176105Sdrh       VdbeCoverageIf(v, pLevel->op==OP_Prev);
63167d176105Sdrh       VdbeCoverageIf(v, pLevel->op==OP_VNext);
631715750a26Sdan       if( pLevel->regBignull ){
631815750a26Sdan         sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
6319bd717a4dSdan         sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
6320db586e48Sdrh         VdbeCoverage(v);
632115750a26Sdan       }
6322c04ea80fSdrh #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
6323c04ea80fSdrh       if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
6324c04ea80fSdrh #endif
63256134b2dfSdrh     }else if( pLevel->addrCont ){
6326a74f5c29Sdan       sqlite3VdbeResolveLabel(v, pLevel->addrCont);
63276b56344dSdrh     }
63280475629dSdrh     if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
632972e8fa42Sdrh       struct InLoop *pIn;
6330e23399fcSdrh       int j;
6331b3190c15Sdrh       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
6332111a6a7dSdrh       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
633381f5ef05Sdrh         assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
633481f5ef05Sdrh                  || pParse->db->mallocFailed );
6335b3190c15Sdrh         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
63368da209b1Sdan         if( pIn->eEndLoopOp!=OP_Noop ){
6337a0368d93Sdrh           if( pIn->nPrefix ){
6338f761d937Sdrh             int bEarlyOut =
6339f761d937Sdrh                 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
6340f761d937Sdrh                  && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
634174ebaadcSdan             if( pLevel->iLeftJoin ){
634274ebaadcSdan               /* For LEFT JOIN queries, cursor pIn->iCur may not have been
634374ebaadcSdan               ** opened yet. This occurs for WHERE clauses such as
634474ebaadcSdan               ** "a = ? AND b IN (...)", where the index is on (a, b). If
634574ebaadcSdan               ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
634674ebaadcSdan               ** never have been coded, but the body of the loop run to
634774ebaadcSdan               ** return the null-row. So, if the cursor is not open yet,
634874ebaadcSdan               ** jump over the OP_Next or OP_Prev instruction about to
634974ebaadcSdan               ** be coded.  */
635074ebaadcSdan               sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
6351f761d937Sdrh                   sqlite3VdbeCurrentAddr(v) + 2 + bEarlyOut);
635274ebaadcSdan               VdbeCoverage(v);
635374ebaadcSdan             }
6354f761d937Sdrh             if( bEarlyOut ){
635514c98a4fSdrh               sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
635614c98a4fSdrh                   sqlite3VdbeCurrentAddr(v)+2,
635714c98a4fSdrh                   pIn->iBase, pIn->nPrefix);
635814c98a4fSdrh               VdbeCoverage(v);
635981f5ef05Sdrh               /* Retarget the OP_IsNull against the left operand of IN so
636081f5ef05Sdrh               ** it jumps past the OP_IfNoHope.  This is because the
636181f5ef05Sdrh               ** OP_IsNull also bypasses the OP_Affinity opcode that is
636281f5ef05Sdrh               ** required by OP_IfNoHope. */
636381f5ef05Sdrh               sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
636414c98a4fSdrh             }
636574ebaadcSdan           }
63662d96b934Sdrh           sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
6367688852abSdrh           VdbeCoverage(v);
6368f1949b66Sdrh           VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
6369f1949b66Sdrh           VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
63708da209b1Sdan         }
6371b3190c15Sdrh         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
6372e23399fcSdrh       }
6373d99f7068Sdrh     }
6374b3190c15Sdrh     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
6375f68621feSdrh     if( pLevel->pRJ ){
6376f68621feSdrh       sqlite3VdbeAddOp3(v, OP_Return, pLevel->pRJ->regReturn, 0, 1);
6377f68621feSdrh       VdbeCoverage(v);
6378f68621feSdrh     }
6379cd8629e4Sdrh     if( pLevel->addrSkip ){
6380076e85f5Sdrh       sqlite3VdbeGoto(v, pLevel->addrSkip);
6381e084f40bSdrh       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
63822e5ef4edSdrh       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
63832e5ef4edSdrh       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
6384cd8629e4Sdrh     }
638541d2e66eSdrh #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
6386f07cf6e2Sdrh     if( pLevel->addrLikeRep ){
638744aebff2Sdrh       sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
638844aebff2Sdrh                         pLevel->addrLikeRep);
6389f07cf6e2Sdrh       VdbeCoverage(v);
6390f07cf6e2Sdrh     }
639141d2e66eSdrh #endif
6392ad2d8307Sdrh     if( pLevel->iLeftJoin ){
6393b40897abSdan       int ws = pLoop->wsFlags;
6394688852abSdrh       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
6395b40897abSdan       assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
6396b40897abSdan       if( (ws & WHERE_IDX_ONLY)==0 ){
639741203c6cSdan         assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
639841203c6cSdan         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
639935451c6aSdrh       }
6400b40897abSdan       if( (ws & WHERE_INDEXED)
64010475629dSdrh        || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
6402b40897abSdan       ){
6403415ac68aSdrh         if( ws & WHERE_MULTI_OR ){
64040475629dSdrh           Index *pIx = pLevel->u.pCoveringIdx;
6405415ac68aSdrh           int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
6406415ac68aSdrh           sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb);
6407415ac68aSdrh           sqlite3VdbeSetP4KeyInfo(pParse, pIx);
6408415ac68aSdrh         }
64093c84ddffSdrh         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
64107f09b3e3Sdrh       }
6411336a5300Sdrh       if( pLevel->op==OP_Return ){
6412336a5300Sdrh         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
6413336a5300Sdrh       }else{
6414076e85f5Sdrh         sqlite3VdbeGoto(v, pLevel->addrFirst);
6415336a5300Sdrh       }
6416d654be80Sdrh       sqlite3VdbeJumpHere(v, addr);
6417ad2d8307Sdrh     }
64186bc69a2dSdrh     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
6419fc8d4f96Sdrh                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
64206b56344dSdrh   }
64219012bcbcSdrh 
6422fd636c75Sdrh   assert( pWInfo->nLevel<=pTabList->nSrc );
6423c01a3c17Sdrh   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
64245f612295Sdrh     int k, last;
6425f8556d01Sdrh     VdbeOp *pOp, *pLastOp;
6426bfca6a40Sdan     Index *pIdx = 0;
64277601294aSdrh     SrcItem *pTabItem = &pTabList->a[pLevel->iFrom];
64289012bcbcSdrh     Table *pTab = pTabItem->pTab;
64295cf590c1Sdrh     assert( pTab!=0 );
64307ba39a92Sdrh     pLoop = pLevel->pWLoop;
6431fc8d4f96Sdrh 
6432a76ac88aSdrh     /* Do RIGHT JOIN processing.  Generate code that will output the
6433a76ac88aSdrh     ** unmatched rows of the right operand of the RIGHT JOIN with
6434a76ac88aSdrh     ** all of the columns of the left operand set to NULL.
6435a76ac88aSdrh     */
643686c1beb4Sdrh     if( pLevel->pRJ ){
6437949e2ab4Sdrh       sqlite3WhereRightJoinLoop(pWInfo, i, pLevel);
6438e21e36ddSdrh       continue;
6439a76ac88aSdrh     }
6440a76ac88aSdrh 
64415f612295Sdrh     /* For a co-routine, change all OP_Column references to the table of
64427b3aa08eSdrh     ** the co-routine into OP_Copy of result contained in a register.
64435f612295Sdrh     ** OP_Rowid becomes OP_Null.
64445f612295Sdrh     */
6445202230efSdrh     if( pTabItem->fg.viaCoroutine ){
6446202230efSdrh       testcase( pParse->db->mallocFailed );
6447202230efSdrh       translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
6448fb785b2cSdan                             pTabItem->regResult, 0);
64495f612295Sdrh       continue;
64505f612295Sdrh     }
64515f612295Sdrh 
6452f0030760Sdrh     /* If this scan uses an index, make VDBE code substitutions to read data
6453f0030760Sdrh     ** from the index instead of from the table where possible.  In some cases
6454f0030760Sdrh     ** this optimization prevents the table from ever being read, which can
6455f0030760Sdrh     ** yield a significant performance boost.
64569012bcbcSdrh     **
64579012bcbcSdrh     ** Calls to the code generator in between sqlite3WhereBegin and
64589012bcbcSdrh     ** sqlite3WhereEnd will have created code that references the table
64599012bcbcSdrh     ** directly.  This loop scans all that code looking for opcodes
64609012bcbcSdrh     ** that reference the table and converts them into opcodes that
64619012bcbcSdrh     ** reference the index.
64629012bcbcSdrh     */
64637ba39a92Sdrh     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
64647ba39a92Sdrh       pIdx = pLoop->u.btree.pIndex;
64657ba39a92Sdrh     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
64660475629dSdrh       pIdx = pLevel->u.pCoveringIdx;
6467bfca6a40Sdan     }
646863c85a7aSdrh     if( pIdx
646963c85a7aSdrh      && !db->mallocFailed
647063c85a7aSdrh     ){
64715e6d90feSdrh       if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
6472f8556d01Sdrh         last = iEnd;
64735e6d90feSdrh       }else{
64745e6d90feSdrh         last = pWInfo->iEndWhere;
64755e6d90feSdrh       }
6476859434d0Sdrh       if( pIdx->bHasExpr ){
6477e70d4583Sdrh         IndexedExpr *p = pParse->pIdxExpr;
6478859434d0Sdrh         while( p ){
6479859434d0Sdrh           if( p->iIdxCur==pLevel->iIdxCur ){
6480859434d0Sdrh             p->iDataCur = -1;
6481859434d0Sdrh             p->iIdxCur = -1;
6482859434d0Sdrh           }
6483859434d0Sdrh           p = p->pIENext;
6484859434d0Sdrh         }
6485859434d0Sdrh       }
6486f8556d01Sdrh       k = pLevel->addrBody + 1;
6487299bf7c2Sdrh #ifdef SQLITE_DEBUG
6488299bf7c2Sdrh       if( db->flags & SQLITE_VdbeAddopTrace ){
6489299bf7c2Sdrh         printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
6490299bf7c2Sdrh       }
6491f8556d01Sdrh       /* Proof that the "+1" on the k value above is safe */
6492f8556d01Sdrh       pOp = sqlite3VdbeGetOp(v, k - 1);
6493f8556d01Sdrh       assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
6494f8556d01Sdrh       assert( pOp->opcode!=OP_Rowid  || pOp->p1!=pLevel->iTabCur );
6495f8556d01Sdrh       assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
6496299bf7c2Sdrh #endif
6497cc04afdaSdrh       pOp = sqlite3VdbeGetOp(v, k);
6498f8556d01Sdrh       pLastOp = pOp + (last - k);
6499e0cc2673Sdrh       assert( pOp<=pLastOp );
6500f8556d01Sdrh       do{
6501f8556d01Sdrh         if( pOp->p1!=pLevel->iTabCur ){
6502f8556d01Sdrh           /* no-op */
6503f8556d01Sdrh         }else if( pOp->opcode==OP_Column
6504092457b1Sdrh #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6505092457b1Sdrh          || pOp->opcode==OP_Offset
6506092457b1Sdrh #endif
6507092457b1Sdrh         ){
6508ee0ec8e1Sdrh           int x = pOp->p2;
6509511717c6Sdrh           assert( pIdx->pTable==pTab );
6510494317adSdrh #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
6511494317adSdrh           if( pOp->opcode==OP_Offset ){
6512494317adSdrh             /* Do not need to translate the column number */
6513494317adSdrh           }else
6514494317adSdrh #endif
6515ee0ec8e1Sdrh           if( !HasRowid(pTab) ){
6516ee0ec8e1Sdrh             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
6517ee0ec8e1Sdrh             x = pPk->aiColumn[x];
65184b92f98cSdrh             assert( x>=0 );
65198e10d74bSdrh           }else{
6520c5f808d8Sdrh             testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
6521b9bcf7caSdrh             x = sqlite3StorageColumnToTable(pTab,x);
6522ee0ec8e1Sdrh           }
6523b9bcf7caSdrh           x = sqlite3TableColumnToIndex(pIdx, x);
65244415628aSdrh           if( x>=0 ){
65254415628aSdrh             pOp->p2 = x;
652621de2e75Sdanielk1977             pOp->p1 = pLevel->iIdxCur;
6527299bf7c2Sdrh             OpcodeRewriteTrace(db, k, pOp);
652875c493f7Sdrh           }else{
652975c493f7Sdrh             /* Unable to translate the table reference into an index
653075c493f7Sdrh             ** reference.  Verify that this is harmless - that the
653175c493f7Sdrh             ** table being referenced really is open.
653275c493f7Sdrh             */
6533a753a3a2Sdrh #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
653475c493f7Sdrh             assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
653575c493f7Sdrh                  || cursorIsOpen(v,pOp->p1,k)
653667aa2318Sdrh                  || pOp->opcode==OP_Offset
653775c493f7Sdrh             );
6538a753a3a2Sdrh #else
6539a753a3a2Sdrh             assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
6540a753a3a2Sdrh                  || cursorIsOpen(v,pOp->p1,k)
6541a753a3a2Sdrh             );
6542a753a3a2Sdrh #endif
654319a775c2Sdrh           }
6544f0863fe5Sdrh         }else if( pOp->opcode==OP_Rowid ){
65459012bcbcSdrh           pOp->p1 = pLevel->iIdxCur;
6546f0863fe5Sdrh           pOp->opcode = OP_IdxRowid;
6547299bf7c2Sdrh           OpcodeRewriteTrace(db, k, pOp);
654831d6fd55Sdrh         }else if( pOp->opcode==OP_IfNullRow ){
654931d6fd55Sdrh           pOp->p1 = pLevel->iIdxCur;
6550299bf7c2Sdrh           OpcodeRewriteTrace(db, k, pOp);
65519012bcbcSdrh         }
6552f8556d01Sdrh #ifdef SQLITE_DEBUG
6553f8556d01Sdrh         k++;
6554f8556d01Sdrh #endif
6555f8556d01Sdrh       }while( (++pOp)<pLastOp );
6556299bf7c2Sdrh #ifdef SQLITE_DEBUG
6557299bf7c2Sdrh       if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
6558299bf7c2Sdrh #endif
65599012bcbcSdrh     }
65609012bcbcSdrh   }
65619012bcbcSdrh 
6562a76ac88aSdrh   /* The "break" point is here, just past the end of the outer loop.
6563a76ac88aSdrh   ** Set it.
6564a76ac88aSdrh   */
6565a76ac88aSdrh   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
6566a76ac88aSdrh 
65679012bcbcSdrh   /* Final cleanup
65689012bcbcSdrh   */
65698b307fbfSdrh   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
657010fe840eSdrh   whereInfoFree(db, pWInfo);
6571a5d06a3dSdrh   pParse->withinRJSubrtn -= nRJ;
657275897234Sdrh   return;
657375897234Sdrh }
6574