Back to index

php5  5.3.10
where.c
Go to the documentation of this file.
00001 /*
00002 ** 2001 September 15
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This module contains C code that generates VDBE code used to process
00013 ** the WHERE clause of SQL statements.
00014 **
00015 ** $Id: where.c 195361 2005-09-07 15:11:33Z iliaa $
00016 */
00017 #include "sqliteInt.h"
00018 
00019 /*
00020 ** The query generator uses an array of instances of this structure to
00021 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
00022 ** clause subexpression is separated from the others by an AND operator.
00023 */
00024 typedef struct ExprInfo ExprInfo;
00025 struct ExprInfo {
00026   Expr *p;                /* Pointer to the subexpression */
00027   u8 indexable;           /* True if this subexprssion is usable by an index */
00028   short int idxLeft;      /* p->pLeft is a column in this table number. -1 if
00029                           ** p->pLeft is not the column of any table */
00030   short int idxRight;     /* p->pRight is a column in this table number. -1 if
00031                           ** p->pRight is not the column of any table */
00032   unsigned prereqLeft;    /* Bitmask of tables referenced by p->pLeft */
00033   unsigned prereqRight;   /* Bitmask of tables referenced by p->pRight */
00034   unsigned prereqAll;     /* Bitmask of tables referenced by p */
00035 };
00036 
00037 /*
00038 ** An instance of the following structure keeps track of a mapping
00039 ** between VDBE cursor numbers and bitmasks.  The VDBE cursor numbers
00040 ** are small integers contained in SrcList_item.iCursor and Expr.iTable
00041 ** fields.  For any given WHERE clause, we want to track which cursors
00042 ** are being used, so we assign a single bit in a 32-bit word to track
00043 ** that cursor.  Then a 32-bit integer is able to show the set of all
00044 ** cursors being used.
00045 */
00046 typedef struct ExprMaskSet ExprMaskSet;
00047 struct ExprMaskSet {
00048   int n;          /* Number of assigned cursor values */
00049   int ix[31];     /* Cursor assigned to each bit */
00050 };
00051 
00052 /*
00053 ** Determine the number of elements in an array.
00054 */
00055 #define ARRAYSIZE(X)  (sizeof(X)/sizeof(X[0]))
00056 
00057 /*
00058 ** This routine is used to divide the WHERE expression into subexpressions
00059 ** separated by the AND operator.
00060 **
00061 ** aSlot[] is an array of subexpressions structures.
00062 ** There are nSlot spaces left in this array.  This routine attempts to
00063 ** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
00064 ** The return value is the number of slots filled.
00065 */
00066 static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
00067   int cnt = 0;
00068   if( pExpr==0 || nSlot<1 ) return 0;
00069   if( nSlot==1 || pExpr->op!=TK_AND ){
00070     aSlot[0].p = pExpr;
00071     return 1;
00072   }
00073   if( pExpr->pLeft->op!=TK_AND ){
00074     aSlot[0].p = pExpr->pLeft;
00075     cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
00076   }else{
00077     cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
00078     cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
00079   }
00080   return cnt;
00081 }
00082 
00083 /*
00084 ** Initialize an expression mask set
00085 */
00086 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
00087 
00088 /*
00089 ** Return the bitmask for the given cursor.  Assign a new bitmask
00090 ** if this is the first time the cursor has been seen.
00091 */
00092 static int getMask(ExprMaskSet *pMaskSet, int iCursor){
00093   int i;
00094   for(i=0; i<pMaskSet->n; i++){
00095     if( pMaskSet->ix[i]==iCursor ) return 1<<i;
00096   }
00097   if( i==pMaskSet->n && i<ARRAYSIZE(pMaskSet->ix) ){
00098     pMaskSet->n++;
00099     pMaskSet->ix[i] = iCursor;
00100     return 1<<i;
00101   }
00102   return 0;
00103 }
00104 
00105 /*
00106 ** Destroy an expression mask set
00107 */
00108 #define freeMaskSet(P)   /* NO-OP */
00109 
00110 /*
00111 ** This routine walks (recursively) an expression tree and generates
00112 ** a bitmask indicating which tables are used in that expression
00113 ** tree.
00114 **
00115 ** In order for this routine to work, the calling function must have
00116 ** previously invoked sqliteExprResolveIds() on the expression.  See
00117 ** the header comment on that routine for additional information.
00118 ** The sqliteExprResolveIds() routines looks for column names and
00119 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
00120 ** the VDBE cursor number of the table.
00121 */
00122 static int exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
00123   unsigned int mask = 0;
00124   if( p==0 ) return 0;
00125   if( p->op==TK_COLUMN ){
00126     mask = getMask(pMaskSet, p->iTable);
00127     if( mask==0 ) mask = -1;
00128     return mask;
00129   }
00130   if( p->pRight ){
00131     mask = exprTableUsage(pMaskSet, p->pRight);
00132   }
00133   if( p->pLeft ){
00134     mask |= exprTableUsage(pMaskSet, p->pLeft);
00135   }
00136   if( p->pList ){
00137     int i;
00138     for(i=0; i<p->pList->nExpr; i++){
00139       mask |= exprTableUsage(pMaskSet, p->pList->a[i].pExpr);
00140     }
00141   }
00142   return mask;
00143 }
00144 
00145 /*
00146 ** Return TRUE if the given operator is one of the operators that is
00147 ** allowed for an indexable WHERE clause.  The allowed operators are
00148 ** "=", "<", ">", "<=", ">=", and "IN".
00149 */
00150 static int allowedOp(int op){
00151   switch( op ){
00152     case TK_LT:
00153     case TK_LE:
00154     case TK_GT:
00155     case TK_GE:
00156     case TK_EQ:
00157     case TK_IN:
00158       return 1;
00159     default:
00160       return 0;
00161   }
00162 }
00163 
00164 /*
00165 ** The input to this routine is an ExprInfo structure with only the
00166 ** "p" field filled in.  The job of this routine is to analyze the
00167 ** subexpression and populate all the other fields of the ExprInfo
00168 ** structure.
00169 */
00170 static void exprAnalyze(ExprMaskSet *pMaskSet, ExprInfo *pInfo){
00171   Expr *pExpr = pInfo->p;
00172   pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
00173   pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
00174   pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
00175   pInfo->indexable = 0;
00176   pInfo->idxLeft = -1;
00177   pInfo->idxRight = -1;
00178   if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
00179     if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
00180       pInfo->idxRight = pExpr->pRight->iTable;
00181       pInfo->indexable = 1;
00182     }
00183     if( pExpr->pLeft->op==TK_COLUMN ){
00184       pInfo->idxLeft = pExpr->pLeft->iTable;
00185       pInfo->indexable = 1;
00186     }
00187   }
00188 }
00189 
00190 /*
00191 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
00192 ** left-most table in the FROM clause of that same SELECT statement and
00193 ** the table has a cursor number of "base".
00194 **
00195 ** This routine attempts to find an index for pTab that generates the
00196 ** correct record sequence for the given ORDER BY clause.  The return value
00197 ** is a pointer to an index that does the job.  NULL is returned if the
00198 ** table has no index that will generate the correct sort order.
00199 **
00200 ** If there are two or more indices that generate the correct sort order
00201 ** and pPreferredIdx is one of those indices, then return pPreferredIdx.
00202 **
00203 ** nEqCol is the number of columns of pPreferredIdx that are used as
00204 ** equality constraints.  Any index returned must have exactly this same
00205 ** set of columns.  The ORDER BY clause only matches index columns beyond the
00206 ** the first nEqCol columns.
00207 **
00208 ** All terms of the ORDER BY clause must be either ASC or DESC.  The
00209 ** *pbRev value is set to 1 if the ORDER BY clause is all DESC and it is
00210 ** set to 0 if the ORDER BY clause is all ASC.
00211 */
00212 static Index *findSortingIndex(
00213   Table *pTab,            /* The table to be sorted */
00214   int base,               /* Cursor number for pTab */
00215   ExprList *pOrderBy,     /* The ORDER BY clause */
00216   Index *pPreferredIdx,   /* Use this index, if possible and not NULL */
00217   int nEqCol,             /* Number of index columns used with == constraints */
00218   int *pbRev              /* Set to 1 if ORDER BY is DESC */
00219 ){
00220   int i, j;
00221   Index *pMatch;
00222   Index *pIdx;
00223   int sortOrder;
00224 
00225   assert( pOrderBy!=0 );
00226   assert( pOrderBy->nExpr>0 );
00227   sortOrder = pOrderBy->a[0].sortOrder & SQLITE_SO_DIRMASK;
00228   for(i=0; i<pOrderBy->nExpr; i++){
00229     Expr *p;
00230     if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=sortOrder ){
00231       /* Indices can only be used if all ORDER BY terms are either
00232       ** DESC or ASC.  Indices cannot be used on a mixture. */
00233       return 0;
00234     }
00235     if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
00236       /* Do not sort by index if there is a COLLATE clause */
00237       return 0;
00238     }
00239     p = pOrderBy->a[i].pExpr;
00240     if( p->op!=TK_COLUMN || p->iTable!=base ){
00241       /* Can not use an index sort on anything that is not a column in the
00242       ** left-most table of the FROM clause */
00243       return 0;
00244     }
00245   }
00246   
00247   /* If we get this far, it means the ORDER BY clause consists only of
00248   ** ascending columns in the left-most table of the FROM clause.  Now
00249   ** check for a matching index.
00250   */
00251   pMatch = 0;
00252   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
00253     int nExpr = pOrderBy->nExpr;
00254     if( pIdx->nColumn < nEqCol || pIdx->nColumn < nExpr ) continue;
00255     for(i=j=0; i<nEqCol; i++){
00256       if( pPreferredIdx->aiColumn[i]!=pIdx->aiColumn[i] ) break;
00257       if( j<nExpr && pOrderBy->a[j].pExpr->iColumn==pIdx->aiColumn[i] ){ j++; }
00258     }
00259     if( i<nEqCol ) continue;
00260     for(i=0; i+j<nExpr; i++){
00261       if( pOrderBy->a[i+j].pExpr->iColumn!=pIdx->aiColumn[i+nEqCol] ) break;
00262     }
00263     if( i+j>=nExpr ){
00264       pMatch = pIdx;
00265       if( pIdx==pPreferredIdx ) break;
00266     }
00267   }
00268   if( pMatch && pbRev ){
00269     *pbRev = sortOrder==SQLITE_SO_DESC;
00270   }
00271   return pMatch;
00272 }
00273 
00274 /*
00275 ** Disable a term in the WHERE clause.  Except, do not disable the term
00276 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
00277 ** or USING clause of that join.
00278 **
00279 ** Consider the term t2.z='ok' in the following queries:
00280 **
00281 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
00282 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
00283 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
00284 **
00285 ** The t2.z='ok' is disabled in the in (2) because it did not originate
00286 ** in the ON clause.  The term is disabled in (3) because it is not part
00287 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
00288 **
00289 ** Disabling a term causes that term to not be tested in the inner loop
00290 ** of the join.  Disabling is an optimization.  We would get the correct
00291 ** results if nothing were ever disabled, but joins might run a little
00292 ** slower.  The trick is to disable as much as we can without disabling
00293 ** too much.  If we disabled in (1), we'd get the wrong answer.
00294 ** See ticket #813.
00295 */
00296 static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
00297   Expr *pExpr = *ppExpr;
00298   if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
00299     *ppExpr = 0;
00300   }
00301 }
00302 
00303 /*
00304 ** Generate the beginning of the loop used for WHERE clause processing.
00305 ** The return value is a pointer to an (opaque) structure that contains
00306 ** information needed to terminate the loop.  Later, the calling routine
00307 ** should invoke sqliteWhereEnd() with the return value of this function
00308 ** in order to complete the WHERE clause processing.
00309 **
00310 ** If an error occurs, this routine returns NULL.
00311 **
00312 ** The basic idea is to do a nested loop, one loop for each table in
00313 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
00314 ** same as a SELECT with only a single table in the FROM clause.)  For
00315 ** example, if the SQL is this:
00316 **
00317 **       SELECT * FROM t1, t2, t3 WHERE ...;
00318 **
00319 ** Then the code generated is conceptually like the following:
00320 **
00321 **      foreach row1 in t1 do       \    Code generated
00322 **        foreach row2 in t2 do      |-- by sqliteWhereBegin()
00323 **          foreach row3 in t3 do   /
00324 **            ...
00325 **          end                     \    Code generated
00326 **        end                        |-- by sqliteWhereEnd()
00327 **      end                         /
00328 **
00329 ** There are Btree cursors associated with each table.  t1 uses cursor
00330 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
00331 ** And so forth.  This routine generates code to open those VDBE cursors
00332 ** and sqliteWhereEnd() generates the code to close them.
00333 **
00334 ** If the WHERE clause is empty, the foreach loops must each scan their
00335 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
00336 ** the tables have indices and there are terms in the WHERE clause that
00337 ** refer to those indices, a complete table scan can be avoided and the
00338 ** code will run much faster.  Most of the work of this routine is checking
00339 ** to see if there are indices that can be used to speed up the loop.
00340 **
00341 ** Terms of the WHERE clause are also used to limit which rows actually
00342 ** make it to the "..." in the middle of the loop.  After each "foreach",
00343 ** terms of the WHERE clause that use only terms in that loop and outer
00344 ** loops are evaluated and if false a jump is made around all subsequent
00345 ** inner loops (or around the "..." if the test occurs within the inner-
00346 ** most loop)
00347 **
00348 ** OUTER JOINS
00349 **
00350 ** An outer join of tables t1 and t2 is conceptally coded as follows:
00351 **
00352 **    foreach row1 in t1 do
00353 **      flag = 0
00354 **      foreach row2 in t2 do
00355 **        start:
00356 **          ...
00357 **          flag = 1
00358 **      end
00359 **      if flag==0 then
00360 **        move the row2 cursor to a null row
00361 **        goto start
00362 **      fi
00363 **    end
00364 **
00365 ** ORDER BY CLAUSE PROCESSING
00366 **
00367 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
00368 ** if there is one.  If there is no ORDER BY clause or if this routine
00369 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
00370 **
00371 ** If an index can be used so that the natural output order of the table
00372 ** scan is correct for the ORDER BY clause, then that index is used and
00373 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
00374 ** unnecessary sort of the result set if an index appropriate for the
00375 ** ORDER BY clause already exists.
00376 **
00377 ** If the where clause loops cannot be arranged to provide the correct
00378 ** output order, then the *ppOrderBy is unchanged.
00379 */
00380 WhereInfo *sqliteWhereBegin(
00381   Parse *pParse,       /* The parser context */
00382   SrcList *pTabList,   /* A list of all tables to be scanned */
00383   Expr *pWhere,        /* The WHERE clause */
00384   int pushKey,         /* If TRUE, leave the table key on the stack */
00385   ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
00386 ){
00387   int i;                     /* Loop counter */
00388   WhereInfo *pWInfo;         /* Will become the return value of this function */
00389   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
00390   int brk, cont = 0;         /* Addresses used during code generation */
00391   int nExpr;           /* Number of subexpressions in the WHERE clause */
00392   int loopMask;        /* One bit set for each outer loop */
00393   int haveKey;         /* True if KEY is on the stack */
00394   ExprMaskSet maskSet; /* The expression mask set */
00395   int iDirectEq[32];   /* Term of the form ROWID==X for the N-th table */
00396   int iDirectLt[32];   /* Term of the form ROWID<X or ROWID<=X */
00397   int iDirectGt[32];   /* Term of the form ROWID>X or ROWID>=X */
00398   ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
00399 
00400   /* pushKey is only allowed if there is a single table (as in an INSERT or
00401   ** UPDATE statement)
00402   */
00403   assert( pushKey==0 || pTabList->nSrc==1 );
00404 
00405   /* Split the WHERE clause into separate subexpressions where each
00406   ** subexpression is separated by an AND operator.  If the aExpr[]
00407   ** array fills up, the last entry might point to an expression which
00408   ** contains additional unfactored AND operators.
00409   */
00410   initMaskSet(&maskSet);
00411   memset(aExpr, 0, sizeof(aExpr));
00412   nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
00413   if( nExpr==ARRAYSIZE(aExpr) ){
00414     sqliteErrorMsg(pParse, "WHERE clause too complex - no more "
00415        "than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
00416     return 0;
00417   }
00418   
00419   /* Allocate and initialize the WhereInfo structure that will become the
00420   ** return value.
00421   */
00422   pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
00423   if( sqlite_malloc_failed ){
00424     sqliteFree(pWInfo);
00425     return 0;
00426   }
00427   pWInfo->pParse = pParse;
00428   pWInfo->pTabList = pTabList;
00429   pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
00430   pWInfo->iBreak = sqliteVdbeMakeLabel(v);
00431 
00432   /* Special case: a WHERE clause that is constant.  Evaluate the
00433   ** expression and either jump over all of the code or fall thru.
00434   */
00435   if( pWhere && (pTabList->nSrc==0 || sqliteExprIsConstant(pWhere)) ){
00436     sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
00437     pWhere = 0;
00438   }
00439 
00440   /* Analyze all of the subexpressions.
00441   */
00442   for(i=0; i<nExpr; i++){
00443     exprAnalyze(&maskSet, &aExpr[i]);
00444 
00445     /* If we are executing a trigger body, remove all references to
00446     ** new.* and old.* tables from the prerequisite masks.
00447     */
00448     if( pParse->trigStack ){
00449       int x;
00450       if( (x = pParse->trigStack->newIdx) >= 0 ){
00451         int mask = ~getMask(&maskSet, x);
00452         aExpr[i].prereqRight &= mask;
00453         aExpr[i].prereqLeft &= mask;
00454         aExpr[i].prereqAll &= mask;
00455       }
00456       if( (x = pParse->trigStack->oldIdx) >= 0 ){
00457         int mask = ~getMask(&maskSet, x);
00458         aExpr[i].prereqRight &= mask;
00459         aExpr[i].prereqLeft &= mask;
00460         aExpr[i].prereqAll &= mask;
00461       }
00462     }
00463   }
00464 
00465   /* Figure out what index to use (if any) for each nested loop.
00466   ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
00467   ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
00468   ** loop. 
00469   **
00470   ** If terms exist that use the ROWID of any table, then set the
00471   ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
00472   ** to the index of the term containing the ROWID.  We always prefer
00473   ** to use a ROWID which can directly access a table rather than an
00474   ** index which requires reading an index first to get the rowid then
00475   ** doing a second read of the actual database table.
00476   **
00477   ** Actually, if there are more than 32 tables in the join, only the
00478   ** first 32 tables are candidates for indices.  This is (again) due
00479   ** to the limit of 32 bits in an integer bitmask.
00480   */
00481   loopMask = 0;
00482   for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
00483     int j;
00484     int iCur = pTabList->a[i].iCursor;    /* The cursor for this table */
00485     int mask = getMask(&maskSet, iCur);   /* Cursor mask for this table */
00486     Table *pTab = pTabList->a[i].pTab;
00487     Index *pIdx;
00488     Index *pBestIdx = 0;
00489     int bestScore = 0;
00490 
00491     /* Check to see if there is an expression that uses only the
00492     ** ROWID field of this table.  For terms of the form ROWID==expr
00493     ** set iDirectEq[i] to the index of the term.  For terms of the
00494     ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
00495     ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
00496     **
00497     ** (Added:) Treat ROWID IN expr like ROWID=expr.
00498     */
00499     pWInfo->a[i].iCur = -1;
00500     iDirectEq[i] = -1;
00501     iDirectLt[i] = -1;
00502     iDirectGt[i] = -1;
00503     for(j=0; j<nExpr; j++){
00504       if( aExpr[j].idxLeft==iCur && aExpr[j].p->pLeft->iColumn<0
00505             && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
00506         switch( aExpr[j].p->op ){
00507           case TK_IN:
00508           case TK_EQ: iDirectEq[i] = j; break;
00509           case TK_LE:
00510           case TK_LT: iDirectLt[i] = j; break;
00511           case TK_GE:
00512           case TK_GT: iDirectGt[i] = j;  break;
00513         }
00514       }
00515       if( aExpr[j].idxRight==iCur && aExpr[j].p->pRight->iColumn<0
00516             && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
00517         switch( aExpr[j].p->op ){
00518           case TK_EQ: iDirectEq[i] = j;  break;
00519           case TK_LE:
00520           case TK_LT: iDirectGt[i] = j;  break;
00521           case TK_GE:
00522           case TK_GT: iDirectLt[i] = j;  break;
00523         }
00524       }
00525     }
00526     if( iDirectEq[i]>=0 ){
00527       loopMask |= mask;
00528       pWInfo->a[i].pIdx = 0;
00529       continue;
00530     }
00531 
00532     /* Do a search for usable indices.  Leave pBestIdx pointing to
00533     ** the "best" index.  pBestIdx is left set to NULL if no indices
00534     ** are usable.
00535     **
00536     ** The best index is determined as follows.  For each of the
00537     ** left-most terms that is fixed by an equality operator, add
00538     ** 8 to the score.  The right-most term of the index may be
00539     ** constrained by an inequality.  Add 1 if for an "x<..." constraint
00540     ** and add 2 for an "x>..." constraint.  Chose the index that
00541     ** gives the best score.
00542     **
00543     ** This scoring system is designed so that the score can later be
00544     ** used to determine how the index is used.  If the score&7 is 0
00545     ** then all constraints are equalities.  If score&1 is not 0 then
00546     ** there is an inequality used as a termination key.  (ex: "x<...")
00547     ** If score&2 is not 0 then there is an inequality used as the
00548     ** start key.  (ex: "x>...").  A score or 4 is the special case
00549     ** of an IN operator constraint.  (ex:  "x IN ...").
00550     **
00551     ** The IN operator (as in "<expr> IN (...)") is treated the same as
00552     ** an equality comparison except that it can only be used on the
00553     ** left-most column of an index and other terms of the WHERE clause
00554     ** cannot be used in conjunction with the IN operator to help satisfy
00555     ** other columns of the index.
00556     */
00557     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
00558       int eqMask = 0;  /* Index columns covered by an x=... term */
00559       int ltMask = 0;  /* Index columns covered by an x<... term */
00560       int gtMask = 0;  /* Index columns covered by an x>... term */
00561       int inMask = 0;  /* Index columns covered by an x IN .. term */
00562       int nEq, m, score;
00563 
00564       if( pIdx->nColumn>32 ) continue;  /* Ignore indices too many columns */
00565       for(j=0; j<nExpr; j++){
00566         if( aExpr[j].idxLeft==iCur 
00567              && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
00568           int iColumn = aExpr[j].p->pLeft->iColumn;
00569           int k;
00570           for(k=0; k<pIdx->nColumn; k++){
00571             if( pIdx->aiColumn[k]==iColumn ){
00572               switch( aExpr[j].p->op ){
00573                 case TK_IN: {
00574                   if( k==0 ) inMask |= 1;
00575                   break;
00576                 }
00577                 case TK_EQ: {
00578                   eqMask |= 1<<k;
00579                   break;
00580                 }
00581                 case TK_LE:
00582                 case TK_LT: {
00583                   ltMask |= 1<<k;
00584                   break;
00585                 }
00586                 case TK_GE:
00587                 case TK_GT: {
00588                   gtMask |= 1<<k;
00589                   break;
00590                 }
00591                 default: {
00592                   /* CANT_HAPPEN */
00593                   assert( 0 );
00594                   break;
00595                 }
00596               }
00597               break;
00598             }
00599           }
00600         }
00601         if( aExpr[j].idxRight==iCur 
00602              && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
00603           int iColumn = aExpr[j].p->pRight->iColumn;
00604           int k;
00605           for(k=0; k<pIdx->nColumn; k++){
00606             if( pIdx->aiColumn[k]==iColumn ){
00607               switch( aExpr[j].p->op ){
00608                 case TK_EQ: {
00609                   eqMask |= 1<<k;
00610                   break;
00611                 }
00612                 case TK_LE:
00613                 case TK_LT: {
00614                   gtMask |= 1<<k;
00615                   break;
00616                 }
00617                 case TK_GE:
00618                 case TK_GT: {
00619                   ltMask |= 1<<k;
00620                   break;
00621                 }
00622                 default: {
00623                   /* CANT_HAPPEN */
00624                   assert( 0 );
00625                   break;
00626                 }
00627               }
00628               break;
00629             }
00630           }
00631         }
00632       }
00633 
00634       /* The following loop ends with nEq set to the number of columns
00635       ** on the left of the index with == constraints.
00636       */
00637       for(nEq=0; nEq<pIdx->nColumn; nEq++){
00638         m = (1<<(nEq+1))-1;
00639         if( (m & eqMask)!=m ) break;
00640       }
00641       score = nEq*8;   /* Base score is 8 times number of == constraints */
00642       m = 1<<nEq;
00643       if( m & ltMask ) score++;    /* Increase score for a < constraint */
00644       if( m & gtMask ) score+=2;   /* Increase score for a > constraint */
00645       if( score==0 && inMask ) score = 4;  /* Default score for IN constraint */
00646       if( score>bestScore ){
00647         pBestIdx = pIdx;
00648         bestScore = score;
00649       }
00650     }
00651     pWInfo->a[i].pIdx = pBestIdx;
00652     pWInfo->a[i].score = bestScore;
00653     pWInfo->a[i].bRev = 0;
00654     loopMask |= mask;
00655     if( pBestIdx ){
00656       pWInfo->a[i].iCur = pParse->nTab++;
00657       pWInfo->peakNTab = pParse->nTab;
00658     }
00659   }
00660 
00661   /* Check to see if the ORDER BY clause is or can be satisfied by the
00662   ** use of an index on the first table.
00663   */
00664   if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
00665      Index *pSortIdx;
00666      Index *pIdx;
00667      Table *pTab;
00668      int bRev = 0;
00669 
00670      pTab = pTabList->a[0].pTab;
00671      pIdx = pWInfo->a[0].pIdx;
00672      if( pIdx && pWInfo->a[0].score==4 ){
00673        /* If there is already an IN index on the left-most table,
00674        ** it will not give the correct sort order.
00675        ** So, pretend that no suitable index is found.
00676        */
00677        pSortIdx = 0;
00678      }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
00679        /* If the left-most column is accessed using its ROWID, then do
00680        ** not try to sort by index.
00681        */
00682        pSortIdx = 0;
00683      }else{
00684        int nEqCol = (pWInfo->a[0].score+4)/8;
00685        pSortIdx = findSortingIndex(pTab, pTabList->a[0].iCursor, 
00686                                    *ppOrderBy, pIdx, nEqCol, &bRev);
00687      }
00688      if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
00689        if( pIdx==0 ){
00690          pWInfo->a[0].pIdx = pSortIdx;
00691          pWInfo->a[0].iCur = pParse->nTab++;
00692          pWInfo->peakNTab = pParse->nTab;
00693        }
00694        pWInfo->a[0].bRev = bRev;
00695        *ppOrderBy = 0;
00696      }
00697   }
00698 
00699   /* Open all tables in the pTabList and all indices used by those tables.
00700   */
00701   for(i=0; i<pTabList->nSrc; i++){
00702     Table *pTab;
00703     Index *pIx;
00704 
00705     pTab = pTabList->a[i].pTab;
00706     if( pTab->isTransient || pTab->pSelect ) continue;
00707     sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
00708     sqliteVdbeOp3(v, OP_OpenRead, pTabList->a[i].iCursor, pTab->tnum,
00709                      pTab->zName, P3_STATIC);
00710     sqliteCodeVerifySchema(pParse, pTab->iDb);
00711     if( (pIx = pWInfo->a[i].pIdx)!=0 ){
00712       sqliteVdbeAddOp(v, OP_Integer, pIx->iDb, 0);
00713       sqliteVdbeOp3(v, OP_OpenRead, pWInfo->a[i].iCur, pIx->tnum, pIx->zName,0);
00714     }
00715   }
00716 
00717   /* Generate the code to do the search
00718   */
00719   loopMask = 0;
00720   for(i=0; i<pTabList->nSrc; i++){
00721     int j, k;
00722     int iCur = pTabList->a[i].iCursor;
00723     Index *pIdx;
00724     WhereLevel *pLevel = &pWInfo->a[i];
00725 
00726     /* If this is the right table of a LEFT OUTER JOIN, allocate and
00727     ** initialize a memory cell that records if this table matches any
00728     ** row of the left table of the join.
00729     */
00730     if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
00731       if( !pParse->nMem ) pParse->nMem++;
00732       pLevel->iLeftJoin = pParse->nMem++;
00733       sqliteVdbeAddOp(v, OP_String, 0, 0);
00734       sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
00735     }
00736 
00737     pIdx = pLevel->pIdx;
00738     pLevel->inOp = OP_Noop;
00739     if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
00740       /* Case 1:  We can directly reference a single row using an
00741       **          equality comparison against the ROWID field.  Or
00742       **          we reference multiple rows using a "rowid IN (...)"
00743       **          construct.
00744       */
00745       k = iDirectEq[i];
00746       assert( k<nExpr );
00747       assert( aExpr[k].p!=0 );
00748       assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
00749       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
00750       if( aExpr[k].idxLeft==iCur ){
00751         Expr *pX = aExpr[k].p;
00752         if( pX->op!=TK_IN ){
00753           sqliteExprCode(pParse, aExpr[k].p->pRight);
00754         }else if( pX->pList ){
00755           sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
00756           pLevel->inOp = OP_SetNext;
00757           pLevel->inP1 = pX->iTable;
00758           pLevel->inP2 = sqliteVdbeCurrentAddr(v);
00759         }else{
00760           assert( pX->pSelect );
00761           sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
00762           sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
00763           pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
00764           pLevel->inOp = OP_Next;
00765           pLevel->inP1 = pX->iTable;
00766         }
00767       }else{
00768         sqliteExprCode(pParse, aExpr[k].p->pLeft);
00769       }
00770       disableTerm(pLevel, &aExpr[k].p);
00771       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
00772       sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
00773       haveKey = 0;
00774       sqliteVdbeAddOp(v, OP_NotExists, iCur, brk);
00775       pLevel->op = OP_Noop;
00776     }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
00777       /* Case 2:  There is an index and all terms of the WHERE clause that
00778       **          refer to the index use the "==" or "IN" operators.
00779       */
00780       int start;
00781       int testOp;
00782       int nColumn = (pLevel->score+4)/8;
00783       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
00784       for(j=0; j<nColumn; j++){
00785         for(k=0; k<nExpr; k++){
00786           Expr *pX = aExpr[k].p;
00787           if( pX==0 ) continue;
00788           if( aExpr[k].idxLeft==iCur
00789              && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight 
00790              && pX->pLeft->iColumn==pIdx->aiColumn[j]
00791           ){
00792             if( pX->op==TK_EQ ){
00793               sqliteExprCode(pParse, pX->pRight);
00794               disableTerm(pLevel, &aExpr[k].p);
00795               break;
00796             }
00797             if( pX->op==TK_IN && nColumn==1 ){
00798               if( pX->pList ){
00799                 sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
00800                 pLevel->inOp = OP_SetNext;
00801                 pLevel->inP1 = pX->iTable;
00802                 pLevel->inP2 = sqliteVdbeCurrentAddr(v);
00803               }else{
00804                 assert( pX->pSelect );
00805                 sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
00806                 sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
00807                 pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
00808                 pLevel->inOp = OP_Next;
00809                 pLevel->inP1 = pX->iTable;
00810               }
00811               disableTerm(pLevel, &aExpr[k].p);
00812               break;
00813             }
00814           }
00815           if( aExpr[k].idxRight==iCur
00816              && aExpr[k].p->op==TK_EQ
00817              && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
00818              && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
00819           ){
00820             sqliteExprCode(pParse, aExpr[k].p->pLeft);
00821             disableTerm(pLevel, &aExpr[k].p);
00822             break;
00823           }
00824         }
00825       }
00826       pLevel->iMem = pParse->nMem++;
00827       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
00828       sqliteVdbeAddOp(v, OP_NotNull, -nColumn, sqliteVdbeCurrentAddr(v)+3);
00829       sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
00830       sqliteVdbeAddOp(v, OP_Goto, 0, brk);
00831       sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
00832       sqliteAddIdxKeyType(v, pIdx);
00833       if( nColumn==pIdx->nColumn || pLevel->bRev ){
00834         sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
00835         testOp = OP_IdxGT;
00836       }else{
00837         sqliteVdbeAddOp(v, OP_Dup, 0, 0);
00838         sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
00839         sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
00840         testOp = OP_IdxGE;
00841       }
00842       if( pLevel->bRev ){
00843         /* Scan in reverse order */
00844         sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
00845         sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
00846         start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
00847         sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
00848         pLevel->op = OP_Prev;
00849       }else{
00850         /* Scan in the forward order */
00851         sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
00852         start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
00853         sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
00854         pLevel->op = OP_Next;
00855       }
00856       sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
00857       sqliteVdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
00858       sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
00859       if( i==pTabList->nSrc-1 && pushKey ){
00860         haveKey = 1;
00861       }else{
00862         sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
00863         haveKey = 0;
00864       }
00865       pLevel->p1 = pLevel->iCur;
00866       pLevel->p2 = start;
00867     }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
00868       /* Case 3:  We have an inequality comparison against the ROWID field.
00869       */
00870       int testOp = OP_Noop;
00871       int start;
00872 
00873       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
00874       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
00875       if( iDirectGt[i]>=0 ){
00876         k = iDirectGt[i];
00877         assert( k<nExpr );
00878         assert( aExpr[k].p!=0 );
00879         assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
00880         if( aExpr[k].idxLeft==iCur ){
00881           sqliteExprCode(pParse, aExpr[k].p->pRight);
00882         }else{
00883           sqliteExprCode(pParse, aExpr[k].p->pLeft);
00884         }
00885         sqliteVdbeAddOp(v, OP_ForceInt,
00886           aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT, brk);
00887         sqliteVdbeAddOp(v, OP_MoveTo, iCur, brk);
00888         disableTerm(pLevel, &aExpr[k].p);
00889       }else{
00890         sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
00891       }
00892       if( iDirectLt[i]>=0 ){
00893         k = iDirectLt[i];
00894         assert( k<nExpr );
00895         assert( aExpr[k].p!=0 );
00896         assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
00897         if( aExpr[k].idxLeft==iCur ){
00898           sqliteExprCode(pParse, aExpr[k].p->pRight);
00899         }else{
00900           sqliteExprCode(pParse, aExpr[k].p->pLeft);
00901         }
00902         /* sqliteVdbeAddOp(v, OP_MustBeInt, 0, sqliteVdbeCurrentAddr(v)+1); */
00903         pLevel->iMem = pParse->nMem++;
00904         sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
00905         if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
00906           testOp = OP_Ge;
00907         }else{
00908           testOp = OP_Gt;
00909         }
00910         disableTerm(pLevel, &aExpr[k].p);
00911       }
00912       start = sqliteVdbeCurrentAddr(v);
00913       pLevel->op = OP_Next;
00914       pLevel->p1 = iCur;
00915       pLevel->p2 = start;
00916       if( testOp!=OP_Noop ){
00917         sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
00918         sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
00919         sqliteVdbeAddOp(v, testOp, 0, brk);
00920       }
00921       haveKey = 0;
00922     }else if( pIdx==0 ){
00923       /* Case 4:  There is no usable index.  We must do a complete
00924       **          scan of the entire database table.
00925       */
00926       int start;
00927 
00928       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
00929       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
00930       sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
00931       start = sqliteVdbeCurrentAddr(v);
00932       pLevel->op = OP_Next;
00933       pLevel->p1 = iCur;
00934       pLevel->p2 = start;
00935       haveKey = 0;
00936     }else{
00937       /* Case 5: The WHERE clause term that refers to the right-most
00938       **         column of the index is an inequality.  For example, if
00939       **         the index is on (x,y,z) and the WHERE clause is of the
00940       **         form "x=5 AND y<10" then this case is used.  Only the
00941       **         right-most column can be an inequality - the rest must
00942       **         use the "==" operator.
00943       **
00944       **         This case is also used when there are no WHERE clause
00945       **         constraints but an index is selected anyway, in order
00946       **         to force the output order to conform to an ORDER BY.
00947       */
00948       int score = pLevel->score;
00949       int nEqColumn = score/8;
00950       int start;
00951       int leFlag, geFlag;
00952       int testOp;
00953 
00954       /* Evaluate the equality constraints
00955       */
00956       for(j=0; j<nEqColumn; j++){
00957         for(k=0; k<nExpr; k++){
00958           if( aExpr[k].p==0 ) continue;
00959           if( aExpr[k].idxLeft==iCur
00960              && aExpr[k].p->op==TK_EQ
00961              && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight 
00962              && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
00963           ){
00964             sqliteExprCode(pParse, aExpr[k].p->pRight);
00965             disableTerm(pLevel, &aExpr[k].p);
00966             break;
00967           }
00968           if( aExpr[k].idxRight==iCur
00969              && aExpr[k].p->op==TK_EQ
00970              && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
00971              && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
00972           ){
00973             sqliteExprCode(pParse, aExpr[k].p->pLeft);
00974             disableTerm(pLevel, &aExpr[k].p);
00975             break;
00976           }
00977         }
00978       }
00979 
00980       /* Duplicate the equality term values because they will all be
00981       ** used twice: once to make the termination key and once to make the
00982       ** start key.
00983       */
00984       for(j=0; j<nEqColumn; j++){
00985         sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
00986       }
00987 
00988       /* Labels for the beginning and end of the loop
00989       */
00990       cont = pLevel->cont = sqliteVdbeMakeLabel(v);
00991       brk = pLevel->brk = sqliteVdbeMakeLabel(v);
00992 
00993       /* Generate the termination key.  This is the key value that
00994       ** will end the search.  There is no termination key if there
00995       ** are no equality terms and no "X<..." term.
00996       **
00997       ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
00998       ** key computed here really ends up being the start key.
00999       */
01000       if( (score & 1)!=0 ){
01001         for(k=0; k<nExpr; k++){
01002           Expr *pExpr = aExpr[k].p;
01003           if( pExpr==0 ) continue;
01004           if( aExpr[k].idxLeft==iCur
01005              && (pExpr->op==TK_LT || pExpr->op==TK_LE)
01006              && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight 
01007              && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
01008           ){
01009             sqliteExprCode(pParse, pExpr->pRight);
01010             leFlag = pExpr->op==TK_LE;
01011             disableTerm(pLevel, &aExpr[k].p);
01012             break;
01013           }
01014           if( aExpr[k].idxRight==iCur
01015              && (pExpr->op==TK_GT || pExpr->op==TK_GE)
01016              && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
01017              && pExpr->pRight->iColumn==pIdx->aiColumn[j]
01018           ){
01019             sqliteExprCode(pParse, pExpr->pLeft);
01020             leFlag = pExpr->op==TK_GE;
01021             disableTerm(pLevel, &aExpr[k].p);
01022             break;
01023           }
01024         }
01025         testOp = OP_IdxGE;
01026       }else{
01027         testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
01028         leFlag = 1;
01029       }
01030       if( testOp!=OP_Noop ){
01031         int nCol = nEqColumn + (score & 1);
01032         pLevel->iMem = pParse->nMem++;
01033         sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
01034         sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
01035         sqliteVdbeAddOp(v, OP_Goto, 0, brk);
01036         sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
01037         sqliteAddIdxKeyType(v, pIdx);
01038         if( leFlag ){
01039           sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
01040         }
01041         if( pLevel->bRev ){
01042           sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
01043         }else{
01044           sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
01045         }
01046       }else if( pLevel->bRev ){
01047         sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
01048       }
01049 
01050       /* Generate the start key.  This is the key that defines the lower
01051       ** bound on the search.  There is no start key if there are no
01052       ** equality terms and if there is no "X>..." term.  In
01053       ** that case, generate a "Rewind" instruction in place of the
01054       ** start key search.
01055       **
01056       ** 2002-Dec-04: In the case of a reverse-order search, the so-called
01057       ** "start" key really ends up being used as the termination key.
01058       */
01059       if( (score & 2)!=0 ){
01060         for(k=0; k<nExpr; k++){
01061           Expr *pExpr = aExpr[k].p;
01062           if( pExpr==0 ) continue;
01063           if( aExpr[k].idxLeft==iCur
01064              && (pExpr->op==TK_GT || pExpr->op==TK_GE)
01065              && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight 
01066              && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
01067           ){
01068             sqliteExprCode(pParse, pExpr->pRight);
01069             geFlag = pExpr->op==TK_GE;
01070             disableTerm(pLevel, &aExpr[k].p);
01071             break;
01072           }
01073           if( aExpr[k].idxRight==iCur
01074              && (pExpr->op==TK_LT || pExpr->op==TK_LE)
01075              && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
01076              && pExpr->pRight->iColumn==pIdx->aiColumn[j]
01077           ){
01078             sqliteExprCode(pParse, pExpr->pLeft);
01079             geFlag = pExpr->op==TK_LE;
01080             disableTerm(pLevel, &aExpr[k].p);
01081             break;
01082           }
01083         }
01084       }else{
01085         geFlag = 1;
01086       }
01087       if( nEqColumn>0 || (score&2)!=0 ){
01088         int nCol = nEqColumn + ((score&2)!=0);
01089         sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
01090         sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
01091         sqliteVdbeAddOp(v, OP_Goto, 0, brk);
01092         sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
01093         sqliteAddIdxKeyType(v, pIdx);
01094         if( !geFlag ){
01095           sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
01096         }
01097         if( pLevel->bRev ){
01098           pLevel->iMem = pParse->nMem++;
01099           sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
01100           testOp = OP_IdxLT;
01101         }else{
01102           sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
01103         }
01104       }else if( pLevel->bRev ){
01105         testOp = OP_Noop;
01106       }else{
01107         sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
01108       }
01109 
01110       /* Generate the the top of the loop.  If there is a termination
01111       ** key we have to test for that key and abort at the top of the
01112       ** loop.
01113       */
01114       start = sqliteVdbeCurrentAddr(v);
01115       if( testOp!=OP_Noop ){
01116         sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
01117         sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
01118       }
01119       sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
01120       sqliteVdbeAddOp(v, OP_IdxIsNull, nEqColumn + (score & 1), cont);
01121       sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
01122       if( i==pTabList->nSrc-1 && pushKey ){
01123         haveKey = 1;
01124       }else{
01125         sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
01126         haveKey = 0;
01127       }
01128 
01129       /* Record the instruction used to terminate the loop.
01130       */
01131       pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
01132       pLevel->p1 = pLevel->iCur;
01133       pLevel->p2 = start;
01134     }
01135     loopMask |= getMask(&maskSet, iCur);
01136 
01137     /* Insert code to test every subexpression that can be completely
01138     ** computed using the current set of tables.
01139     */
01140     for(j=0; j<nExpr; j++){
01141       if( aExpr[j].p==0 ) continue;
01142       if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
01143       if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
01144         continue;
01145       }
01146       if( haveKey ){
01147         haveKey = 0;
01148         sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
01149       }
01150       sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
01151       aExpr[j].p = 0;
01152     }
01153     brk = cont;
01154 
01155     /* For a LEFT OUTER JOIN, generate code that will record the fact that
01156     ** at least one row of the right table has matched the left table.  
01157     */
01158     if( pLevel->iLeftJoin ){
01159       pLevel->top = sqliteVdbeCurrentAddr(v);
01160       sqliteVdbeAddOp(v, OP_Integer, 1, 0);
01161       sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
01162       for(j=0; j<nExpr; j++){
01163         if( aExpr[j].p==0 ) continue;
01164         if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
01165         if( haveKey ){
01166           /* Cannot happen.  "haveKey" can only be true if pushKey is true
01167           ** an pushKey can only be true for DELETE and UPDATE and there are
01168           ** no outer joins with DELETE and UPDATE.
01169           */
01170           haveKey = 0;
01171           sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
01172         }
01173         sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
01174         aExpr[j].p = 0;
01175       }
01176     }
01177   }
01178   pWInfo->iContinue = cont;
01179   if( pushKey && !haveKey ){
01180     sqliteVdbeAddOp(v, OP_Recno, pTabList->a[0].iCursor, 0);
01181   }
01182   freeMaskSet(&maskSet);
01183   return pWInfo;
01184 }
01185 
01186 /*
01187 ** Generate the end of the WHERE loop.  See comments on 
01188 ** sqliteWhereBegin() for additional information.
01189 */
01190 void sqliteWhereEnd(WhereInfo *pWInfo){
01191   Vdbe *v = pWInfo->pParse->pVdbe;
01192   int i;
01193   WhereLevel *pLevel;
01194   SrcList *pTabList = pWInfo->pTabList;
01195 
01196   for(i=pTabList->nSrc-1; i>=0; i--){
01197     pLevel = &pWInfo->a[i];
01198     sqliteVdbeResolveLabel(v, pLevel->cont);
01199     if( pLevel->op!=OP_Noop ){
01200       sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
01201     }
01202     sqliteVdbeResolveLabel(v, pLevel->brk);
01203     if( pLevel->inOp!=OP_Noop ){
01204       sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
01205     }
01206     if( pLevel->iLeftJoin ){
01207       int addr;
01208       addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
01209       sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
01210       sqliteVdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
01211       if( pLevel->iCur>=0 ){
01212         sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
01213       }
01214       sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
01215     }
01216   }
01217   sqliteVdbeResolveLabel(v, pWInfo->iBreak);
01218   for(i=0; i<pTabList->nSrc; i++){
01219     Table *pTab = pTabList->a[i].pTab;
01220     assert( pTab!=0 );
01221     if( pTab->isTransient || pTab->pSelect ) continue;
01222     pLevel = &pWInfo->a[i];
01223     sqliteVdbeAddOp(v, OP_Close, pTabList->a[i].iCursor, 0);
01224     if( pLevel->pIdx!=0 ){
01225       sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
01226     }
01227   }
01228 #if 0  /* Never reuse a cursor */
01229   if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
01230     pWInfo->pParse->nTab = pWInfo->savedNTab;
01231   }
01232 #endif
01233   sqliteFree(pWInfo);
01234   return;
01235 }