AryaWu/sqlite
0
1/*2** 2001 September 153**4** The author disclaims copyright to this source code. In place of5** a legal notice, here is a blessing:6**7** May you do good and not evil.8** May you find forgiveness for yourself and forgive others.9** May you share freely, never taking more than you give.10**11*************************************************************************12** This module contains C code that generates VDBE code used to process13** the WHERE clause of SQL statements. This module is responsible for14** generating the code that loops through a table looking for applicable15** rows. Indices are selected and used to speed the search when doing16** so is applicable. Because this module is responsible for selecting17** indices, you might also think of this module as the "query optimizer".18*/19#include "sqliteInt.h"20#include "whereInt.h"21 22/*23** Extra information appended to the end of sqlite3_index_info but not24** visible to the xBestIndex function, at least not directly. The25** sqlite3_vtab_collation() interface knows how to reach it, however.26**27** This object is not an API and can be changed from one release to the28** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()29** agree on the structure, all will be well.30*/31typedef struct HiddenIndexInfo HiddenIndexInfo;32struct HiddenIndexInfo {33 WhereClause *pWC; /* The Where clause being analyzed */34 Parse *pParse; /* The parsing context */35 int eDistinct; /* Value to return from sqlite3_vtab_distinct() */36 u32 mIn; /* Mask of terms that are <col> IN (...) */37 u32 mHandleIn; /* Terms that vtab will handle as <col> IN (...) */38 sqlite3_value *aRhs[FLEXARRAY]; /* RHS values for constraints. MUST BE LAST39 ** Extra space is allocated to hold up40 ** to nTerm such values */41};42 43/* Size (in bytes) of a HiddenIndeInfo object sufficient to hold as44** many as N constraints */45#define SZ_HIDDENINDEXINFO(N) \46 (offsetof(HiddenIndexInfo,aRhs) + (N)*sizeof(sqlite3_value*))47 48/* Forward declaration of methods */49static int whereLoopResize(sqlite3*, WhereLoop*, int);50 51/*52** Return the estimated number of output rows from a WHERE clause53*/54LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){55 return pWInfo->nRowOut;56}57 58/*59** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this60** WHERE clause returns outputs for DISTINCT processing.61*/62int sqlite3WhereIsDistinct(WhereInfo *pWInfo){63 return pWInfo->eDistinct;64}65 66/*67** Return the number of ORDER BY terms that are satisfied by the68** WHERE clause. A return of 0 means that the output must be69** completely sorted. A return equal to the number of ORDER BY70** terms means that no sorting is needed at all. A return that71** is positive but less than the number of ORDER BY terms means that72** block sorting is required.73*/74int sqlite3WhereIsOrdered(WhereInfo *pWInfo){75 return pWInfo->nOBSat<0 ? 0 : pWInfo->nOBSat;76}77 78/*79** In the ORDER BY LIMIT optimization, if the inner-most loop is known80** to emit rows in increasing order, and if the last row emitted by the81** inner-most loop did not fit within the sorter, then we can skip all82** subsequent rows for the current iteration of the inner loop (because they83** will not fit in the sorter either) and continue with the second inner84** loop - the loop immediately outside the inner-most.85**86** When a row does not fit in the sorter (because the sorter already87** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the88** label returned by this function.89**90** If the ORDER BY LIMIT optimization applies, the jump destination should91** be the continuation for the second-inner-most loop. If the ORDER BY92** LIMIT optimization does not apply, then the jump destination should93** be the continuation for the inner-most loop.94**95** It is always safe for this routine to return the continuation of the96** inner-most loop, in the sense that a correct answer will result. 97** Returning the continuation the second inner loop is an optimization98** that might make the code run a little faster, but should not change99** the final answer.100*/101int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){102 WhereLevel *pInner;103 if( !pWInfo->bOrderedInnerLoop ){104 /* The ORDER BY LIMIT optimization does not apply. Jump to the105 ** continuation of the inner-most loop. */106 return pWInfo->iContinue;107 }108 pInner = &pWInfo->a[pWInfo->nLevel-1];109 assert( pInner->addrNxt!=0 );110 return pInner->pRJ ? pWInfo->iContinue : pInner->addrNxt;111}112 113/*114** While generating code for the min/max optimization, after handling115** the aggregate-step call to min() or max(), check to see if any116** additional looping is required. If the output order is such that117** we are certain that the correct answer has already been found, then118** code an OP_Goto to by pass subsequent processing.119**120** Any extra OP_Goto that is coded here is an optimization. The121** correct answer should be obtained regardless. This OP_Goto just122** makes the answer appear faster.123*/124void sqlite3WhereMinMaxOptEarlyOut(Vdbe *v, WhereInfo *pWInfo){125 WhereLevel *pInner;126 int i;127 if( !pWInfo->bOrderedInnerLoop ) return;128 if( pWInfo->nOBSat==0 ) return;129 for(i=pWInfo->nLevel-1; i>=0; i--){130 pInner = &pWInfo->a[i];131 if( (pInner->pWLoop->wsFlags & WHERE_COLUMN_IN)!=0 ){132 sqlite3VdbeGoto(v, pInner->addrNxt);133 return;134 }135 }136 sqlite3VdbeGoto(v, pWInfo->iBreak);137}138 139/*140** Return the VDBE address or label to jump to in order to continue141** immediately with the next row of a WHERE clause.142*/143int sqlite3WhereContinueLabel(WhereInfo *pWInfo){144 assert( pWInfo->iContinue!=0 );145 return pWInfo->iContinue;146}147 148/*149** Return the VDBE address or label to jump to in order to break150** out of a WHERE loop.151*/152int sqlite3WhereBreakLabel(WhereInfo *pWInfo){153 return pWInfo->iBreak;154}155 156/*157** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to158** operate directly on the rowids returned by a WHERE clause. Return159** ONEPASS_SINGLE (1) if the statement can operation directly because only160** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass161** optimization can be used on multiple162**163** If the ONEPASS optimization is used (if this routine returns true)164** then also write the indices of open cursors used by ONEPASS165** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data166** table and iaCur[1] gets the cursor used by an auxiliary index.167** Either value may be -1, indicating that cursor is not used.168** Any cursors returned will have been opened for writing.169**170** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is171** unable to use the ONEPASS optimization.172*/173int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){174 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);175#ifdef WHERETRACE_ENABLED176 if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){177 sqlite3DebugPrintf("%s cursors: %d %d\n",178 pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",179 aiCur[0], aiCur[1]);180 }181#endif182 return pWInfo->eOnePass;183}184 185/*186** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move187** the data cursor to the row selected by the index cursor.188*/189int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){190 return pWInfo->bDeferredSeek;191}192 193/*194** Move the content of pSrc into pDest195*/196static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){197 pDest->n = pSrc->n;198 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));199}200 201/*202** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.203**204** The new entry might overwrite an existing entry, or it might be205** appended, or it might be discarded. Do whatever is the right thing206** so that pSet keeps the N_OR_COST best entries seen so far.207*/208static int whereOrInsert(209 WhereOrSet *pSet, /* The WhereOrSet to be updated */210 Bitmask prereq, /* Prerequisites of the new entry */211 LogEst rRun, /* Run-cost of the new entry */212 LogEst nOut /* Number of outputs for the new entry */213){214 u16 i;215 WhereOrCost *p;216 for(i=pSet->n, p=pSet->a; i>0; i--, p++){217 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){218 goto whereOrInsert_done;219 }220 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){221 return 0;222 }223 }224 if( pSet->n<N_OR_COST ){225 p = &pSet->a[pSet->n++];226 p->nOut = nOut;227 }else{228 p = pSet->a;229 for(i=1; i<pSet->n; i++){230 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;231 }232 if( p->rRun<=rRun ) return 0;233 }234whereOrInsert_done:235 p->prereq = prereq;236 p->rRun = rRun;237 if( p->nOut>nOut ) p->nOut = nOut;238 return 1;239}240 241/*242** Return the bitmask for the given cursor number. Return 0 if243** iCursor is not in the set.244*/245Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){246 int i;247 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );248 assert( pMaskSet->n>0 || pMaskSet->ix[0]<0 );249 assert( iCursor>=-1 );250 if( pMaskSet->ix[0]==iCursor ){251 return 1;252 }253 for(i=1; i<pMaskSet->n; i++){254 if( pMaskSet->ix[i]==iCursor ){255 return MASKBIT(i);256 }257 }258 return 0;259}260 261/* Allocate memory that is automatically freed when pWInfo is freed.262*/263void *sqlite3WhereMalloc(WhereInfo *pWInfo, u64 nByte){264 WhereMemBlock *pBlock;265 pBlock = sqlite3DbMallocRawNN(pWInfo->pParse->db, nByte+sizeof(*pBlock));266 if( pBlock ){267 pBlock->pNext = pWInfo->pMemToFree;268 pBlock->sz = nByte;269 pWInfo->pMemToFree = pBlock;270 pBlock++;271 }272 return (void*)pBlock;273}274void *sqlite3WhereRealloc(WhereInfo *pWInfo, void *pOld, u64 nByte){275 void *pNew = sqlite3WhereMalloc(pWInfo, nByte);276 if( pNew && pOld ){277 WhereMemBlock *pOldBlk = (WhereMemBlock*)pOld;278 pOldBlk--;279 assert( pOldBlk->sz<nByte );280 memcpy(pNew, pOld, pOldBlk->sz);281 }282 return pNew;283}284 285/*286** Create a new mask for cursor iCursor.287**288** There is one cursor per table in the FROM clause. The number of289** tables in the FROM clause is limited by a test early in the290** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]291** array will never overflow.292*/293static void createMask(WhereMaskSet *pMaskSet, int iCursor){294 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );295 pMaskSet->ix[pMaskSet->n++] = iCursor;296}297 298/*299** If the right-hand branch of the expression is a TK_COLUMN, then return300** a pointer to the right-hand branch. Otherwise, return NULL.301*/302static Expr *whereRightSubexprIsColumn(Expr *p){303 p = sqlite3ExprSkipCollateAndLikely(p->pRight);304 if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){305 return p;306 }307 return 0;308}309 310/*311** Term pTerm is guaranteed to be a WO_IN term. It may be a component term312** of a vector IN expression of the form "(x, y, ...) IN (SELECT ...)".313** This function checks to see if the term is compatible with an index314** column with affinity idxaff (one of the SQLITE_AFF_XYZ values). If so,315** it returns a pointer to the name of the collation sequence (e.g. "BINARY"316** or "NOCASE") used by the comparison in pTerm. If it is not compatible317** with affinity idxaff, NULL is returned.318*/319static SQLITE_NOINLINE const char *indexInAffinityOk(320 Parse *pParse, 321 WhereTerm *pTerm, 322 u8 idxaff323){324 Expr *pX = pTerm->pExpr;325 Expr inexpr;326 327 assert( pTerm->eOperator & WO_IN );328 329 if( sqlite3ExprIsVector(pX->pLeft) ){330 int iField = pTerm->u.x.iField - 1;331 inexpr.flags = 0;332 inexpr.op = TK_EQ;333 inexpr.pLeft = pX->pLeft->x.pList->a[iField].pExpr;334 assert( ExprUseXSelect(pX) );335 inexpr.pRight = pX->x.pSelect->pEList->a[iField].pExpr;336 pX = &inexpr;337 }338 339 if( sqlite3IndexAffinityOk(pX, idxaff) ){340 CollSeq *pRet = sqlite3ExprCompareCollSeq(pParse, pX);341 return pRet ? pRet->zName : sqlite3StrBINARY;342 }343 return 0;344}345 346/*347** Advance to the next WhereTerm that matches according to the criteria348** established when the pScan object was initialized by whereScanInit().349** Return NULL if there are no more matching WhereTerms.350*/351static WhereTerm *whereScanNext(WhereScan *pScan){352 int iCur; /* The cursor on the LHS of the term */353 i16 iColumn; /* The column on the LHS of the term. -1 for IPK */354 Expr *pX; /* An expression being tested */355 WhereClause *pWC; /* Shorthand for pScan->pWC */356 WhereTerm *pTerm; /* The term being tested */357 int k = pScan->k; /* Where to start scanning */358 359 assert( pScan->iEquiv<=pScan->nEquiv );360 pWC = pScan->pWC;361 while(1){362 iColumn = pScan->aiColumn[pScan->iEquiv-1];363 iCur = pScan->aiCur[pScan->iEquiv-1];364 assert( pWC!=0 );365 assert( iCur>=0 );366 do{367 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){368 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 || pTerm->leftCursor<0 );369 if( pTerm->leftCursor==iCur370 && pTerm->u.x.leftColumn==iColumn371 && (iColumn!=XN_EXPR372 || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,373 pScan->pIdxExpr,iCur)==0)374 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON))375 ){376 if( (pTerm->eOperator & WO_EQUIV)!=0377 && pScan->nEquiv<ArraySize(pScan->aiCur)378 && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0379 ){380 int j;381 for(j=0; j<pScan->nEquiv; j++){382 if( pScan->aiCur[j]==pX->iTable383 && pScan->aiColumn[j]==pX->iColumn ){384 break;385 }386 }387 if( j==pScan->nEquiv ){388 pScan->aiCur[j] = pX->iTable;389 pScan->aiColumn[j] = pX->iColumn;390 pScan->nEquiv++;391 }392 }393 if( (pTerm->eOperator & pScan->opMask)!=0 ){394 /* Verify the affinity and collating sequence match */395 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){396 const char *zCollName;397 Parse *pParse = pWC->pWInfo->pParse;398 pX = pTerm->pExpr;399 400 if( (pTerm->eOperator & WO_IN) ){401 zCollName = indexInAffinityOk(pParse, pTerm, pScan->idxaff);402 if( !zCollName ) continue;403 }else{404 CollSeq *pColl;405 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){406 continue;407 }408 assert(pX->pLeft);409 pColl = sqlite3ExprCompareCollSeq(pParse, pX);410 zCollName = pColl ? pColl->zName : sqlite3StrBINARY;411 }412 413 if( sqlite3StrICmp(zCollName, pScan->zCollName) ){414 continue;415 }416 }417 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0418 && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))419 && pX->op==TK_COLUMN420 && pX->iTable==pScan->aiCur[0]421 && pX->iColumn==pScan->aiColumn[0]422 ){423 testcase( pTerm->eOperator & WO_IS );424 continue;425 }426 pScan->pWC = pWC;427 pScan->k = k+1;428#ifdef WHERETRACE_ENABLED429 if( (sqlite3WhereTrace & 0x20000)!=0 && pScan->nEquiv>1 ){430 int ii;431 sqlite3DebugPrintf("EQUIVALENT TO {%d:%d} (due to TERM-%d):",432 pScan->aiCur[0], pScan->aiColumn[0], pTerm->iTerm);433 for(ii=1; ii<pScan->nEquiv; ii++){434 sqlite3DebugPrintf(" {%d:%d}",435 pScan->aiCur[ii], pScan->aiColumn[ii]);436 }437 sqlite3DebugPrintf("\n");438 }439#endif440 return pTerm;441 }442 }443 }444 pWC = pWC->pOuter;445 k = 0;446 }while( pWC!=0 );447 if( pScan->iEquiv>=pScan->nEquiv ) break;448 pWC = pScan->pOrigWC;449 k = 0;450 pScan->iEquiv++;451 }452 return 0;453}454 455/*456** This is whereScanInit() for the case of an index on an expression.457** It is factored out into a separate tail-recursion subroutine so that458** the normal whereScanInit() routine, which is a high-runner, does not459** need to push registers onto the stack as part of its prologue.460*/461static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){462 pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);463 return whereScanNext(pScan);464}465 466/*467** Initialize a WHERE clause scanner object. Return a pointer to the468** first match. Return NULL if there are no matches.469**470** The scanner will be searching the WHERE clause pWC. It will look471** for terms of the form "X <op> <expr>" where X is column iColumn of table472** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx473** must be one of the indexes of table iCur.474**475** The <op> must be one of the operators described by opMask.476**477** If the search is for X and the WHERE clause contains terms of the478** form X=Y then this routine might also return terms of the form479** "Y <op> <expr>". The number of levels of transitivity is limited,480** but is enough to handle most commonly occurring SQL statements.481**482** If X is not the INTEGER PRIMARY KEY then X must be compatible with483** index pIdx.484*/485static WhereTerm *whereScanInit(486 WhereScan *pScan, /* The WhereScan object being initialized */487 WhereClause *pWC, /* The WHERE clause to be scanned */488 int iCur, /* Cursor to scan for */489 int iColumn, /* Column to scan for */490 u32 opMask, /* Operator(s) to scan for */491 Index *pIdx /* Must be compatible with this index */492){493 pScan->pOrigWC = pWC;494 pScan->pWC = pWC;495 pScan->pIdxExpr = 0;496 pScan->idxaff = 0;497 pScan->zCollName = 0;498 pScan->opMask = opMask;499 pScan->k = 0;500 pScan->aiCur[0] = iCur;501 pScan->nEquiv = 1;502 pScan->iEquiv = 1;503 if( pIdx ){504 int j = iColumn;505 iColumn = pIdx->aiColumn[j];506 if( iColumn==pIdx->pTable->iPKey ){507 iColumn = XN_ROWID;508 }else if( iColumn>=0 ){509 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;510 pScan->zCollName = pIdx->azColl[j];511 }else if( iColumn==XN_EXPR ){512 pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;513 pScan->zCollName = pIdx->azColl[j];514 pScan->aiColumn[0] = XN_EXPR;515 return whereScanInitIndexExpr(pScan);516 }517 }else if( iColumn==XN_EXPR ){518 return 0;519 }520 pScan->aiColumn[0] = iColumn;521 return whereScanNext(pScan);522}523 524/*525** Search for a term in the WHERE clause that is of the form "X <op> <expr>"526** where X is a reference to the iColumn of table iCur or of index pIdx527** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by528** the op parameter. Return a pointer to the term. Return 0 if not found.529**530** If pIdx!=0 then it must be one of the indexes of table iCur. 531** Search for terms matching the iColumn-th column of pIdx532** rather than the iColumn-th column of table iCur.533**534** The term returned might by Y=<expr> if there is another constraint in535** the WHERE clause that specifies that X=Y. Any such constraints will be536** identified by the WO_EQUIV bit in the pTerm->eOperator field. The537** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11538** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10539** other equivalent values. Hence a search for X will return <expr> if X=A1540** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.541**542** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"543** then try for the one with no dependencies on <expr> - in other words where544** <expr> is a constant expression of some kind. Only return entries of545** the form "X <op> Y" where Y is a column in another table if no terms of546** the form "X <op> <const-expr>" exist. If no terms with a constant RHS547** exist, try to return a term that does not use WO_EQUIV.548*/549WhereTerm *sqlite3WhereFindTerm(550 WhereClause *pWC, /* The WHERE clause to be searched */551 int iCur, /* Cursor number of LHS */552 int iColumn, /* Column number of LHS */553 Bitmask notReady, /* RHS must not overlap with this mask */554 u32 op, /* Mask of WO_xx values describing operator */555 Index *pIdx /* Must be compatible with this index, if not NULL */556){557 WhereTerm *pResult = 0;558 WhereTerm *p;559 WhereScan scan;560 561 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);562 op &= WO_EQ|WO_IS;563 while( p ){564 if( (p->prereqRight & notReady)==0 ){565 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){566 testcase( p->eOperator & WO_IS );567 return p;568 }569 if( pResult==0 ) pResult = p;570 }571 p = whereScanNext(&scan);572 }573 return pResult;574}575 576/*577** This function searches pList for an entry that matches the iCol-th column578** of index pIdx.579**580** If such an expression is found, its index in pList->a[] is returned. If581** no expression is found, -1 is returned.582*/583static int findIndexCol(584 Parse *pParse, /* Parse context */585 ExprList *pList, /* Expression list to search */586 int iBase, /* Cursor for table associated with pIdx */587 Index *pIdx, /* Index to match column of */588 int iCol /* Column of index to match */589){590 int i;591 const char *zColl = pIdx->azColl[iCol];592 593 for(i=0; i<pList->nExpr; i++){594 Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);595 if( ALWAYS(p!=0)596 && (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)597 && p->iColumn==pIdx->aiColumn[iCol]598 && p->iTable==iBase599 ){600 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);601 if( 0==sqlite3StrICmp(pColl->zName, zColl) ){602 return i;603 }604 }605 }606 607 return -1;608}609 610/*611** Return TRUE if the iCol-th column of index pIdx is NOT NULL612*/613static int indexColumnNotNull(Index *pIdx, int iCol){614 int j;615 assert( pIdx!=0 );616 assert( iCol>=0 && iCol<pIdx->nColumn );617 j = pIdx->aiColumn[iCol];618 if( j>=0 ){619 return pIdx->pTable->aCol[j].notNull;620 }else if( j==(-1) ){621 return 1;622 }else{623 assert( j==(-2) );624 return 0; /* Assume an indexed expression can always yield a NULL */625 626 }627}628 629/*630** Return true if the DISTINCT expression-list passed as the third argument631** is redundant.632**633** A DISTINCT list is redundant if any subset of the columns in the634** DISTINCT list are collectively unique and individually non-null.635*/636static int isDistinctRedundant(637 Parse *pParse, /* Parsing context */638 SrcList *pTabList, /* The FROM clause */639 WhereClause *pWC, /* The WHERE clause */640 ExprList *pDistinct /* The result set that needs to be DISTINCT */641){642 Table *pTab;643 Index *pIdx;644 int i; 645 int iBase;646 647 /* If there is more than one table or sub-select in the FROM clause of648 ** this query, then it will not be possible to show that the DISTINCT649 ** clause is redundant. */650 if( pTabList->nSrc!=1 ) return 0;651 iBase = pTabList->a[0].iCursor;652 pTab = pTabList->a[0].pSTab;653 654 /* If any of the expressions is an IPK column on table iBase, then return655 ** true. Note: The (p->iTable==iBase) part of this test may be false if the656 ** current SELECT is a correlated sub-query.657 */658 for(i=0; i<pDistinct->nExpr; i++){659 Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);660 if( NEVER(p==0) ) continue;661 if( p->op!=TK_COLUMN && p->op!=TK_AGG_COLUMN ) continue;662 if( p->iTable==iBase && p->iColumn<0 ) return 1;663 }664 665 /* Loop through all indices on the table, checking each to see if it makes666 ** the DISTINCT qualifier redundant. It does so if:667 **668 ** 1. The index is itself UNIQUE, and669 **670 ** 2. All of the columns in the index are either part of the pDistinct671 ** list, or else the WHERE clause contains a term of the form "col=X",672 ** where X is a constant value. The collation sequences of the673 ** comparison and select-list expressions must match those of the index.674 **675 ** 3. All of those index columns for which the WHERE clause does not676 ** contain a "col=X" term are subject to a NOT NULL constraint.677 */678 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){679 if( !IsUniqueIndex(pIdx) ) continue;680 if( pIdx->pPartIdxWhere ) continue;681 for(i=0; i<pIdx->nKeyCol; i++){682 if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){683 if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;684 if( indexColumnNotNull(pIdx, i)==0 ) break;685 }686 }687 if( i==pIdx->nKeyCol ){688 /* This index implies that the DISTINCT qualifier is redundant. */689 return 1;690 }691 }692 693 return 0;694}695 696 697/*698** Estimate the logarithm of the input value to base 2.699*/700static LogEst estLog(LogEst N){701 return N<=10 ? 0 : sqlite3LogEst(N) - 33;702}703 704/*705** Convert OP_Column opcodes to OP_Copy in previously generated code.706**707** This routine runs over generated VDBE code and translates OP_Column708** opcodes into OP_Copy when the table is being accessed via co-routine709** instead of via table lookup.710**711** If the iAutoidxCur is not zero, then any OP_Rowid instructions on712** cursor iTabCur are transformed into OP_Sequence opcode for the713** iAutoidxCur cursor, in order to generate unique rowids for the714** automatic index being generated.715*/716static void translateColumnToCopy(717 Parse *pParse, /* Parsing context */718 int iStart, /* Translate from this opcode to the end */719 int iTabCur, /* OP_Column/OP_Rowid references to this table */720 int iRegister, /* The first column is in this register */721 int iAutoidxCur /* If non-zero, cursor of autoindex being generated */722){723 Vdbe *v = pParse->pVdbe;724 VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);725 int iEnd = sqlite3VdbeCurrentAddr(v);726 if( pParse->db->mallocFailed ) return;727#ifdef SQLITE_DEBUG728 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){729 printf("CHECKING for column-to-copy on cursor %d for %d..%d\n",730 iTabCur, iStart, iEnd);731 }732#endif733 for(; iStart<iEnd; iStart++, pOp++){734 if( pOp->p1!=iTabCur ) continue;735 if( pOp->opcode==OP_Column ){736#ifdef SQLITE_DEBUG737 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){738 printf("TRANSLATE OP_Column to OP_Copy at %d\n", iStart);739 }740#endif741 pOp->opcode = OP_Copy;742 pOp->p1 = pOp->p2 + iRegister;743 pOp->p2 = pOp->p3;744 pOp->p3 = 0;745 pOp->p5 = 2; /* Cause the MEM_Subtype flag to be cleared */746 }else if( pOp->opcode==OP_Rowid ){747#ifdef SQLITE_DEBUG748 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){749 printf("TRANSLATE OP_Rowid to OP_Sequence at %d\n", iStart);750 }751#endif752 pOp->opcode = OP_Sequence;753 pOp->p1 = iAutoidxCur;754#ifdef SQLITE_ALLOW_ROWID_IN_VIEW755 if( iAutoidxCur==0 ){756 pOp->opcode = OP_Null;757 pOp->p3 = 0;758 }759#endif760 }761 }762}763 764/*765** Two routines for printing the content of an sqlite3_index_info766** structure. Used for testing and debugging only. If neither767** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines768** are no-ops.769*/770#if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)771static void whereTraceIndexInfoInputs(772 sqlite3_index_info *p, /* The IndexInfo object */773 Table *pTab /* The TABLE that is the virtual table */774){775 int i;776 if( (sqlite3WhereTrace & 0x10)==0 ) return;777 sqlite3DebugPrintf("sqlite3_index_info inputs for %s:\n", pTab->zName);778 for(i=0; i<p->nConstraint; i++){779 sqlite3DebugPrintf(780 " constraint[%d]: col=%d termid=%d op=%d usabled=%d collseq=%s\n",781 i,782 p->aConstraint[i].iColumn,783 p->aConstraint[i].iTermOffset,784 p->aConstraint[i].op,785 p->aConstraint[i].usable,786 sqlite3_vtab_collation(p,i));787 }788 for(i=0; i<p->nOrderBy; i++){789 sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",790 i,791 p->aOrderBy[i].iColumn,792 p->aOrderBy[i].desc);793 }794}795static void whereTraceIndexInfoOutputs(796 sqlite3_index_info *p, /* The IndexInfo object */797 Table *pTab /* The TABLE that is the virtual table */798){799 int i;800 if( (sqlite3WhereTrace & 0x10)==0 ) return;801 sqlite3DebugPrintf("sqlite3_index_info outputs for %s:\n", pTab->zName);802 for(i=0; i<p->nConstraint; i++){803 sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",804 i,805 p->aConstraintUsage[i].argvIndex,806 p->aConstraintUsage[i].omit);807 }808 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);809 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);810 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);811 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);812 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);813}814#else815#define whereTraceIndexInfoInputs(A,B)816#define whereTraceIndexInfoOutputs(A,B)817#endif818 819/*820** We know that pSrc is an operand of an outer join. Return true if821** pTerm is a constraint that is compatible with that join.822**823** pTerm must be EP_OuterON if pSrc is the right operand of an824** outer join. pTerm can be either EP_OuterON or EP_InnerON if pSrc825** is the left operand of a RIGHT join.826**827** See https://sqlite.org/forum/forumpost/206d99a16dd9212f828** for an example of a WHERE clause constraints that may not be used on829** the right table of a RIGHT JOIN because the constraint implies a830** not-NULL condition on the left table of the RIGHT JOIN.831*/832static int constraintCompatibleWithOuterJoin(833 const WhereTerm *pTerm, /* WHERE clause term to check */834 const SrcItem *pSrc /* Table we are trying to access */835){836 assert( (pSrc->fg.jointype&(JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 ); /* By caller */837 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LEFT );838 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LTORJ );839 testcase( ExprHasProperty(pTerm->pExpr, EP_OuterON) )840 testcase( ExprHasProperty(pTerm->pExpr, EP_InnerON) );841 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON)842 || pTerm->pExpr->w.iJoin != pSrc->iCursor843 ){844 return 0;845 }846 if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0847 && NEVER(ExprHasProperty(pTerm->pExpr, EP_InnerON))848 ){849 return 0;850 }851 return 1;852}853 854#ifndef SQLITE_OMIT_AUTOMATIC_INDEX855/*856** Return true if column iCol of table pTab seem like it might be a857** good column to use as part of a query-time index.858**859** Current algorithm (subject to improvement!):860**861** 1. If iCol is already the left-most column of some other index,862** then return false.863**864** 2. If iCol is part of an existing index that has an aiRowLogEst of865** more than 20, then return false.866**867** 3. If no disqualifying conditions above are found, return true.868**869** 2025-01-03: I experimented with a new rule that returns false if the870** the datatype of the column is "BOOLEAN". This did not improve871** performance on any queries at hand, but it did burn CPU cycles, so the872** idea was not committed.873*/874static SQLITE_NOINLINE int columnIsGoodIndexCandidate(875 const Table *pTab,876 int iCol877){878 const Index *pIdx;879 for(pIdx = pTab->pIndex; pIdx!=0; pIdx=pIdx->pNext){880 int j;881 for(j=0; j<pIdx->nKeyCol; j++){882 if( pIdx->aiColumn[j]==iCol ){883 if( j==0 ) return 0;884 if( pIdx->hasStat1 && pIdx->aiRowLogEst[j+1]>20 ) return 0;885 break;886 }887 }888 }889 return 1;890}891#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */892 893 894 895#ifndef SQLITE_OMIT_AUTOMATIC_INDEX896/*897** Return TRUE if the WHERE clause term pTerm is of a form where it898** could be used with an index to access pSrc, assuming an appropriate899** index existed.900*/901static int termCanDriveIndex(902 const WhereTerm *pTerm, /* WHERE clause term to check */903 const SrcItem *pSrc, /* Table we are trying to access */904 const Bitmask notReady /* Tables in outer loops of the join */905){906 char aff;907 int leftCol;908 909 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;910 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;911 assert( (pSrc->fg.jointype & JT_RIGHT)==0 );912 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0913 && !constraintCompatibleWithOuterJoin(pTerm,pSrc)914 ){915 return 0; /* See https://sqlite.org/forum/forumpost/51e6959f61 */916 }917 if( (pTerm->prereqRight & notReady)!=0 ) return 0;918 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );919 leftCol = pTerm->u.x.leftColumn;920 if( leftCol<0 ) return 0;921 aff = pSrc->pSTab->aCol[leftCol].affinity;922 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;923 testcase( pTerm->pExpr->op==TK_IS );924 return columnIsGoodIndexCandidate(pSrc->pSTab, leftCol);925}926#endif927 928 929#ifndef SQLITE_OMIT_AUTOMATIC_INDEX930 931#ifdef SQLITE_ENABLE_STMT_SCANSTATUS932/*933** Argument pIdx represents an automatic index that the current statement934** will create and populate. Add an OP_Explain with text of the form:935**936** CREATE AUTOMATIC INDEX ON <table>(<cols>) [WHERE <expr>]937**938** This is only required if sqlite3_stmt_scanstatus() is enabled, to939** associate an SQLITE_SCANSTAT_NCYCLE and SQLITE_SCANSTAT_NLOOP940** values with. In order to avoid breaking legacy code and test cases,941** the OP_Explain is not added if this is an EXPLAIN QUERY PLAN command.942*/943static void explainAutomaticIndex(944 Parse *pParse,945 Index *pIdx, /* Automatic index to explain */946 int bPartial, /* True if pIdx is a partial index */947 int *pAddrExplain /* OUT: Address of OP_Explain */948){949 if( IS_STMT_SCANSTATUS(pParse->db) && pParse->explain!=2 ){950 Table *pTab = pIdx->pTable;951 const char *zSep = "";952 char *zText = 0;953 int ii = 0;954 sqlite3_str *pStr = sqlite3_str_new(pParse->db);955 sqlite3_str_appendf(pStr,"CREATE AUTOMATIC INDEX ON %s(", pTab->zName);956 assert( pIdx->nColumn>1 );957 assert( pIdx->aiColumn[pIdx->nColumn-1]==XN_ROWID || !HasRowid(pTab) );958 for(ii=0; ii<(pIdx->nColumn-1); ii++){959 const char *zName = 0;960 int iCol = pIdx->aiColumn[ii];961 962 zName = pTab->aCol[iCol].zCnName;963 sqlite3_str_appendf(pStr, "%s%s", zSep, zName);964 zSep = ", ";965 }966 zText = sqlite3_str_finish(pStr);967 if( zText==0 ){968 sqlite3OomFault(pParse->db);969 }else{970 *pAddrExplain = sqlite3VdbeExplain(971 pParse, 0, "%s)%s", zText, (bPartial ? " WHERE <expr>" : "")972 );973 sqlite3_free(zText);974 }975 }976}977#else978# define explainAutomaticIndex(a,b,c,d)979#endif980 981/*982** Generate code to construct the Index object for an automatic index983** and to set up the WhereLevel object pLevel so that the code generator984** makes use of the automatic index.985*/986static SQLITE_NOINLINE void constructAutomaticIndex(987 Parse *pParse, /* The parsing context */988 WhereClause *pWC, /* The WHERE clause */989 const Bitmask notReady, /* Mask of cursors that are not available */990 WhereLevel *pLevel /* Write new index here */991){992 int nKeyCol; /* Number of columns in the constructed index */993 WhereTerm *pTerm; /* A single term of the WHERE clause */994 WhereTerm *pWCEnd; /* End of pWC->a[] */995 Index *pIdx; /* Object describing the transient index */996 Vdbe *v; /* Prepared statement under construction */997 int addrInit; /* Address of the initialization bypass jump */998 Table *pTable; /* The table being indexed */999 int addrTop; /* Top of the index fill loop */1000 int regRecord; /* Register holding an index record */1001 int n; /* Column counter */1002 int i; /* Loop counter */1003 int mxBitCol; /* Maximum column in pSrc->colUsed */1004 CollSeq *pColl; /* Collating sequence to on a column */1005 WhereLoop *pLoop; /* The Loop object */1006 char *zNotUsed; /* Extra space on the end of pIdx */1007 Bitmask idxCols; /* Bitmap of columns used for indexing */1008 Bitmask extraCols; /* Bitmap of additional columns */1009 u8 sentWarning = 0; /* True if a warning has been issued */1010 u8 useBloomFilter = 0; /* True to also add a Bloom filter */1011 Expr *pPartial = 0; /* Partial Index Expression */1012 int iContinue = 0; /* Jump here to skip excluded rows */1013 SrcList *pTabList; /* The complete FROM clause */1014 SrcItem *pSrc; /* The FROM clause term to get the next index */1015 int addrCounter = 0; /* Address where integer counter is initialized */1016 int regBase; /* Array of registers where record is assembled */1017#ifdef SQLITE_ENABLE_STMT_SCANSTATUS1018 int addrExp = 0; /* Address of OP_Explain */1019#endif1020 1021 /* Generate code to skip over the creation and initialization of the1022 ** transient index on 2nd and subsequent iterations of the loop. */1023 v = pParse->pVdbe;1024 assert( v!=0 );1025 addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);1026 1027 /* Count the number of columns that will be added to the index1028 ** and used to match WHERE clause constraints */1029 nKeyCol = 0;1030 pTabList = pWC->pWInfo->pTabList;1031 pSrc = &pTabList->a[pLevel->iFrom];1032 pTable = pSrc->pSTab;1033 pWCEnd = &pWC->a[pWC->nTerm];1034 pLoop = pLevel->pWLoop;1035 idxCols = 0;1036 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){1037 Expr *pExpr = pTerm->pExpr;1038 /* Make the automatic index a partial index if there are terms in the1039 ** WHERE clause (or the ON clause of a LEFT join) that constrain which1040 ** rows of the target table (pSrc) that can be used. */1041 if( (pTerm->wtFlags & TERM_VIRTUAL)==01042 && sqlite3ExprIsSingleTableConstraint(pExpr, pTabList, pLevel->iFrom, 0)1043 ){1044 pPartial = sqlite3ExprAnd(pParse, pPartial,1045 sqlite3ExprDup(pParse->db, pExpr, 0));1046 }1047 if( termCanDriveIndex(pTerm, pSrc, notReady) ){1048 int iCol;1049 Bitmask cMask;1050 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );1051 iCol = pTerm->u.x.leftColumn;1052 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);1053 testcase( iCol==BMS );1054 testcase( iCol==BMS-1 );1055 if( !sentWarning ){1056 sqlite3_log(SQLITE_WARNING_AUTOINDEX,1057 "automatic index on %s(%s)", pTable->zName,1058 pTable->aCol[iCol].zCnName);1059 sentWarning = 1;1060 }1061 if( (idxCols & cMask)==0 ){1062 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){1063 goto end_auto_index_create;1064 }1065 pLoop->aLTerm[nKeyCol++] = pTerm;1066 idxCols |= cMask;1067 }1068 }1069 }1070 assert( nKeyCol>0 || pParse->db->mallocFailed );1071 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;1072 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED1073 | WHERE_AUTO_INDEX;1074 1075 /* Count the number of additional columns needed to create a1076 ** covering index. A "covering index" is an index that contains all1077 ** columns that are needed by the query. With a covering index, the1078 ** original table never needs to be accessed. Automatic indices must1079 ** be a covering index because the index will not be updated if the1080 ** original table changes and the index and table cannot both be used1081 ** if they go out of sync.1082 */1083 if( IsView(pTable) ){1084 extraCols = ALLBITS & ~idxCols;1085 }else{1086 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));1087 }1088 if( !HasRowid(pTable) ){1089 /* For WITHOUT ROWID tables, ensure that all PRIMARY KEY columns are1090 ** either in the idxCols mask or in the extraCols mask */1091 for(i=0; i<pTable->nCol; i++){1092 if( (pTable->aCol[i].colFlags & COLFLAG_PRIMKEY)==0 ) continue;1093 if( i>=BMS-1 ){1094 extraCols |= MASKBIT(BMS-1);1095 break;1096 }1097 if( idxCols & MASKBIT(i) ) continue;1098 extraCols |= MASKBIT(i);1099 }1100 }1101 mxBitCol = MIN(BMS-1,pTable->nCol);1102 testcase( pTable->nCol==BMS-1 );1103 testcase( pTable->nCol==BMS-2 );1104 for(i=0; i<mxBitCol; i++){1105 if( extraCols & MASKBIT(i) ) nKeyCol++;1106 }1107 if( pSrc->colUsed & MASKBIT(BMS-1) ){1108 nKeyCol += pTable->nCol - BMS + 1;1109 }1110 1111 /* Construct the Index object to describe this index */1112 assert( nKeyCol <= pTable->nCol + MAX(0, pTable->nCol - BMS + 1) );1113 /* ^-- This guarantees that the number of index columns will fit in the u16 */1114 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+HasRowid(pTable),1115 0, &zNotUsed);1116 if( pIdx==0 ) goto end_auto_index_create;1117 pLoop->u.btree.pIndex = pIdx;1118 pIdx->zName = "auto-index";1119 pIdx->pTable = pTable;1120 n = 0;1121 idxCols = 0;1122 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){1123 if( termCanDriveIndex(pTerm, pSrc, notReady) ){1124 int iCol;1125 Bitmask cMask;1126 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );1127 iCol = pTerm->u.x.leftColumn;1128 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);1129 testcase( iCol==BMS-1 );1130 testcase( iCol==BMS );1131 if( (idxCols & cMask)==0 ){1132 Expr *pX = pTerm->pExpr;1133 idxCols |= cMask;1134 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;1135 pColl = sqlite3ExprCompareCollSeq(pParse, pX);1136 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */1137 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;1138 n++;1139 if( ALWAYS(pX->pLeft!=0)1140 && sqlite3ExprAffinity(pX->pLeft)!=SQLITE_AFF_TEXT1141 ){1142 /* TUNING: only use a Bloom filter on an automatic index1143 ** if one or more key columns has the ability to hold numeric1144 ** values, since strings all have the same hash in the Bloom1145 ** filter implementation and hence a Bloom filter on a text column1146 ** is not usually helpful. */1147 useBloomFilter = 1;1148 }1149 }1150 }1151 }1152 assert( (u32)n==pLoop->u.btree.nEq );1153 1154 /* Add additional columns needed to make the automatic index into1155 ** a covering index */1156 for(i=0; i<mxBitCol; i++){1157 if( extraCols & MASKBIT(i) ){1158 pIdx->aiColumn[n] = i;1159 pIdx->azColl[n] = sqlite3StrBINARY;1160 n++;1161 }1162 }1163 if( pSrc->colUsed & MASKBIT(BMS-1) ){1164 for(i=BMS-1; i<pTable->nCol; i++){1165 pIdx->aiColumn[n] = i;1166 pIdx->azColl[n] = sqlite3StrBINARY;1167 n++;1168 }1169 }1170 assert( n==nKeyCol );1171 if( HasRowid(pTable) ){1172 pIdx->aiColumn[n] = XN_ROWID;1173 pIdx->azColl[n] = sqlite3StrBINARY;1174 }1175 1176 /* Create the automatic index */1177 explainAutomaticIndex(pParse, pIdx, pPartial!=0, &addrExp);1178 assert( pLevel->iIdxCur>=0 );1179 pLevel->iIdxCur = pParse->nTab++;1180 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);1181 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);1182 VdbeComment((v, "for %s", pTable->zName));1183 if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) && useBloomFilter ){1184 sqlite3WhereExplainBloomFilter(pParse, pWC->pWInfo, pLevel);1185 pLevel->regFilter = ++pParse->nMem;1186 sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);1187 }1188 1189 /* Fill the automatic index with content */1190 assert( pSrc == &pWC->pWInfo->pTabList->a[pLevel->iFrom] );1191 if( pSrc->fg.viaCoroutine ){1192 int regYield;1193 Subquery *pSubq;1194 assert( pSrc->fg.isSubquery );1195 pSubq = pSrc->u4.pSubq;1196 assert( pSubq!=0 );1197 regYield = pSubq->regReturn;1198 addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);1199 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSubq->addrFillSub);1200 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);