1 /* 2 ** 2015-06-06 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** 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 process 13 ** the WHERE clause of SQL statements. 14 ** 15 ** This file was split off from where.c on 2015-06-06 in order to reduce the 16 ** size of where.c and make it easier to edit. This file contains the routines 17 ** that actually generate the bulk of the WHERE loop code. The original where.c 18 ** file retains the code that does query planning and analysis. 19 */ 20 #include "sqliteInt.h" 21 #include "whereInt.h" 22 23 #ifndef SQLITE_OMIT_EXPLAIN 24 25 /* 26 ** Return the name of the i-th column of the pIdx index. 27 */ 28 static const char *explainIndexColumnName(Index *pIdx, int i){ 29 i = pIdx->aiColumn[i]; 30 if( i==XN_EXPR ) return "<expr>"; 31 if( i==XN_ROWID ) return "rowid"; 32 return pIdx->pTable->aCol[i].zName; 33 } 34 35 /* 36 ** This routine is a helper for explainIndexRange() below 37 ** 38 ** pStr holds the text of an expression that we are building up one term 39 ** at a time. This routine adds a new term to the end of the expression. 40 ** Terms are separated by AND so add the "AND" text for second and subsequent 41 ** terms only. 42 */ 43 static void explainAppendTerm( 44 StrAccum *pStr, /* The text expression being built */ 45 Index *pIdx, /* Index to read column names from */ 46 int nTerm, /* Number of terms */ 47 int iTerm, /* Zero-based index of first term. */ 48 int bAnd, /* Non-zero to append " AND " */ 49 const char *zOp /* Name of the operator */ 50 ){ 51 int i; 52 53 assert( nTerm>=1 ); 54 if( bAnd ) sqlite3_str_append(pStr, " AND ", 5); 55 56 if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1); 57 for(i=0; i<nTerm; i++){ 58 if( i ) sqlite3_str_append(pStr, ",", 1); 59 sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i)); 60 } 61 if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1); 62 63 sqlite3_str_append(pStr, zOp, 1); 64 65 if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1); 66 for(i=0; i<nTerm; i++){ 67 if( i ) sqlite3_str_append(pStr, ",", 1); 68 sqlite3_str_append(pStr, "?", 1); 69 } 70 if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1); 71 } 72 73 /* 74 ** Argument pLevel describes a strategy for scanning table pTab. This 75 ** function appends text to pStr that describes the subset of table 76 ** rows scanned by the strategy in the form of an SQL expression. 77 ** 78 ** For example, if the query: 79 ** 80 ** SELECT * FROM t1 WHERE a=1 AND b>2; 81 ** 82 ** is run and there is an index on (a, b), then this function returns a 83 ** string similar to: 84 ** 85 ** "a=? AND b>?" 86 */ 87 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){ 88 Index *pIndex = pLoop->u.btree.pIndex; 89 u16 nEq = pLoop->u.btree.nEq; 90 u16 nSkip = pLoop->nSkip; 91 int i, j; 92 93 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; 94 sqlite3_str_append(pStr, " (", 2); 95 for(i=0; i<nEq; i++){ 96 const char *z = explainIndexColumnName(pIndex, i); 97 if( i ) sqlite3_str_append(pStr, " AND ", 5); 98 sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z); 99 } 100 101 j = i; 102 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ 103 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">"); 104 i = 1; 105 } 106 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ 107 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<"); 108 } 109 sqlite3_str_append(pStr, ")", 1); 110 } 111 112 /* 113 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN 114 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was 115 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 116 ** is added to the output to describe the table scan strategy in pLevel. 117 ** 118 ** If an OP_Explain opcode is added to the VM, its address is returned. 119 ** Otherwise, if no OP_Explain is coded, zero is returned. 120 */ 121 int sqlite3WhereExplainOneScan( 122 Parse *pParse, /* Parse context */ 123 SrcList *pTabList, /* Table list this loop refers to */ 124 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ 125 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ 126 ){ 127 int ret = 0; 128 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) 129 if( sqlite3ParseToplevel(pParse)->explain==2 ) 130 #endif 131 { 132 SrcItem *pItem = &pTabList->a[pLevel->iFrom]; 133 Vdbe *v = pParse->pVdbe; /* VM being constructed */ 134 sqlite3 *db = pParse->db; /* Database handle */ 135 int isSearch; /* True for a SEARCH. False for SCAN. */ 136 WhereLoop *pLoop; /* The controlling WhereLoop object */ 137 u32 flags; /* Flags that describe this loop */ 138 char *zMsg; /* Text to add to EQP output */ 139 StrAccum str; /* EQP output string */ 140 char zBuf[100]; /* Initial space for EQP output string */ 141 142 pLoop = pLevel->pWLoop; 143 flags = pLoop->wsFlags; 144 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0; 145 146 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 147 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) 148 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); 149 150 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); 151 str.printfFlags = SQLITE_PRINTF_INTERNAL; 152 sqlite3_str_appendf(&str, "%s %S", isSearch ? "SEARCH" : "SCAN", pItem); 153 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ 154 const char *zFmt = 0; 155 Index *pIdx; 156 157 assert( pLoop->u.btree.pIndex!=0 ); 158 pIdx = pLoop->u.btree.pIndex; 159 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); 160 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ 161 if( isSearch ){ 162 zFmt = "PRIMARY KEY"; 163 } 164 }else if( flags & WHERE_PARTIALIDX ){ 165 zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; 166 }else if( flags & WHERE_AUTO_INDEX ){ 167 zFmt = "AUTOMATIC COVERING INDEX"; 168 }else if( flags & WHERE_IDX_ONLY ){ 169 zFmt = "COVERING INDEX %s"; 170 }else{ 171 zFmt = "INDEX %s"; 172 } 173 if( zFmt ){ 174 sqlite3_str_append(&str, " USING ", 7); 175 sqlite3_str_appendf(&str, zFmt, pIdx->zName); 176 explainIndexRange(&str, pLoop); 177 } 178 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ 179 const char *zRangeOp; 180 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ 181 zRangeOp = "="; 182 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ 183 zRangeOp = ">? AND rowid<"; 184 }else if( flags&WHERE_BTM_LIMIT ){ 185 zRangeOp = ">"; 186 }else{ 187 assert( flags&WHERE_TOP_LIMIT); 188 zRangeOp = "<"; 189 } 190 sqlite3_str_appendf(&str, 191 " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); 192 } 193 #ifndef SQLITE_OMIT_VIRTUALTABLE 194 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ 195 sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s", 196 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); 197 } 198 #endif 199 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS 200 if( pLoop->nOut>=10 ){ 201 sqlite3_str_appendf(&str, " (~%llu rows)", 202 sqlite3LogEstToInt(pLoop->nOut)); 203 }else{ 204 sqlite3_str_append(&str, " (~1 row)", 9); 205 } 206 #endif 207 zMsg = sqlite3StrAccumFinish(&str); 208 sqlite3ExplainBreakpoint("",zMsg); 209 ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v), 210 pParse->addrExplain, 0, zMsg,P4_DYNAMIC); 211 } 212 return ret; 213 } 214 #endif /* SQLITE_OMIT_EXPLAIN */ 215 216 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 217 /* 218 ** Configure the VM passed as the first argument with an 219 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 220 ** implement level pLvl. Argument pSrclist is a pointer to the FROM 221 ** clause that the scan reads data from. 222 ** 223 ** If argument addrExplain is not 0, it must be the address of an 224 ** OP_Explain instruction that describes the same loop. 225 */ 226 void sqlite3WhereAddScanStatus( 227 Vdbe *v, /* Vdbe to add scanstatus entry to */ 228 SrcList *pSrclist, /* FROM clause pLvl reads data from */ 229 WhereLevel *pLvl, /* Level to add scanstatus() entry for */ 230 int addrExplain /* Address of OP_Explain (or 0) */ 231 ){ 232 const char *zObj = 0; 233 WhereLoop *pLoop = pLvl->pWLoop; 234 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ 235 zObj = pLoop->u.btree.pIndex->zName; 236 }else{ 237 zObj = pSrclist->a[pLvl->iFrom].zName; 238 } 239 sqlite3VdbeScanStatus( 240 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj 241 ); 242 } 243 #endif 244 245 246 /* 247 ** Disable a term in the WHERE clause. Except, do not disable the term 248 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON 249 ** or USING clause of that join. 250 ** 251 ** Consider the term t2.z='ok' in the following queries: 252 ** 253 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' 254 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' 255 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' 256 ** 257 ** The t2.z='ok' is disabled in the in (2) because it originates 258 ** in the ON clause. The term is disabled in (3) because it is not part 259 ** of a LEFT OUTER JOIN. In (1), the term is not disabled. 260 ** 261 ** Disabling a term causes that term to not be tested in the inner loop 262 ** of the join. Disabling is an optimization. When terms are satisfied 263 ** by indices, we disable them to prevent redundant tests in the inner 264 ** loop. We would get the correct results if nothing were ever disabled, 265 ** but joins might run a little slower. The trick is to disable as much 266 ** as we can without disabling too much. If we disabled in (1), we'd get 267 ** the wrong answer. See ticket #813. 268 ** 269 ** If all the children of a term are disabled, then that term is also 270 ** automatically disabled. In this way, terms get disabled if derived 271 ** virtual terms are tested first. For example: 272 ** 273 ** x GLOB 'abc*' AND x>='abc' AND x<'acd' 274 ** \___________/ \______/ \_____/ 275 ** parent child1 child2 276 ** 277 ** Only the parent term was in the original WHERE clause. The child1 278 ** and child2 terms were added by the LIKE optimization. If both of 279 ** the virtual child terms are valid, then testing of the parent can be 280 ** skipped. 281 ** 282 ** Usually the parent term is marked as TERM_CODED. But if the parent 283 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. 284 ** The TERM_LIKECOND marking indicates that the term should be coded inside 285 ** a conditional such that is only evaluated on the second pass of a 286 ** LIKE-optimization loop, when scanning BLOBs instead of strings. 287 */ 288 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ 289 int nLoop = 0; 290 assert( pTerm!=0 ); 291 while( (pTerm->wtFlags & TERM_CODED)==0 292 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) 293 && (pLevel->notReady & pTerm->prereqAll)==0 294 ){ 295 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ 296 pTerm->wtFlags |= TERM_LIKECOND; 297 }else{ 298 pTerm->wtFlags |= TERM_CODED; 299 } 300 if( pTerm->iParent<0 ) break; 301 pTerm = &pTerm->pWC->a[pTerm->iParent]; 302 assert( pTerm!=0 ); 303 pTerm->nChild--; 304 if( pTerm->nChild!=0 ) break; 305 nLoop++; 306 } 307 } 308 309 /* 310 ** Code an OP_Affinity opcode to apply the column affinity string zAff 311 ** to the n registers starting at base. 312 ** 313 ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which 314 ** are no-ops) at the beginning and end of zAff are ignored. If all entries 315 ** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated. 316 ** 317 ** This routine makes its own copy of zAff so that the caller is free 318 ** to modify zAff after this routine returns. 319 */ 320 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ 321 Vdbe *v = pParse->pVdbe; 322 if( zAff==0 ){ 323 assert( pParse->db->mallocFailed ); 324 return; 325 } 326 assert( v!=0 ); 327 328 /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE 329 ** entries at the beginning and end of the affinity string. 330 */ 331 assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB ); 332 while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){ 333 n--; 334 base++; 335 zAff++; 336 } 337 while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){ 338 n--; 339 } 340 341 /* Code the OP_Affinity opcode if there is anything left to do. */ 342 if( n>0 ){ 343 sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n); 344 } 345 } 346 347 /* 348 ** Expression pRight, which is the RHS of a comparison operation, is 349 ** either a vector of n elements or, if n==1, a scalar expression. 350 ** Before the comparison operation, affinity zAff is to be applied 351 ** to the pRight values. This function modifies characters within the 352 ** affinity string to SQLITE_AFF_BLOB if either: 353 ** 354 ** * the comparison will be performed with no affinity, or 355 ** * the affinity change in zAff is guaranteed not to change the value. 356 */ 357 static void updateRangeAffinityStr( 358 Expr *pRight, /* RHS of comparison */ 359 int n, /* Number of vector elements in comparison */ 360 char *zAff /* Affinity string to modify */ 361 ){ 362 int i; 363 for(i=0; i<n; i++){ 364 Expr *p = sqlite3VectorFieldSubexpr(pRight, i); 365 if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB 366 || sqlite3ExprNeedsNoAffinityChange(p, zAff[i]) 367 ){ 368 zAff[i] = SQLITE_AFF_BLOB; 369 } 370 } 371 } 372 373 374 /* 375 ** pX is an expression of the form: (vector) IN (SELECT ...) 376 ** In other words, it is a vector IN operator with a SELECT clause on the 377 ** LHS. But not all terms in the vector are indexable and the terms might 378 ** not be in the correct order for indexing. 379 ** 380 ** This routine makes a copy of the input pX expression and then adjusts 381 ** the vector on the LHS with corresponding changes to the SELECT so that 382 ** the vector contains only index terms and those terms are in the correct 383 ** order. The modified IN expression is returned. The caller is responsible 384 ** for deleting the returned expression. 385 ** 386 ** Example: 387 ** 388 ** CREATE TABLE t1(a,b,c,d,e,f); 389 ** CREATE INDEX t1x1 ON t1(e,c); 390 ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2) 391 ** \_______________________________________/ 392 ** The pX expression 393 ** 394 ** Since only columns e and c can be used with the index, in that order, 395 ** the modified IN expression that is returned will be: 396 ** 397 ** (e,c) IN (SELECT z,x FROM t2) 398 ** 399 ** The reduced pX is different from the original (obviously) and thus is 400 ** only used for indexing, to improve performance. The original unaltered 401 ** IN expression must also be run on each output row for correctness. 402 */ 403 static Expr *removeUnindexableInClauseTerms( 404 Parse *pParse, /* The parsing context */ 405 int iEq, /* Look at loop terms starting here */ 406 WhereLoop *pLoop, /* The current loop */ 407 Expr *pX /* The IN expression to be reduced */ 408 ){ 409 sqlite3 *db = pParse->db; 410 Expr *pNew; 411 pNew = sqlite3ExprDup(db, pX, 0); 412 if( db->mallocFailed==0 ){ 413 ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */ 414 ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */ 415 ExprList *pRhs = 0; /* New RHS after modifications */ 416 ExprList *pLhs = 0; /* New LHS after mods */ 417 int i; /* Loop counter */ 418 Select *pSelect; /* Pointer to the SELECT on the RHS */ 419 420 for(i=iEq; i<pLoop->nLTerm; i++){ 421 if( pLoop->aLTerm[i]->pExpr==pX ){ 422 int iField = pLoop->aLTerm[i]->u.x.iField - 1; 423 if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */ 424 pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr); 425 pOrigRhs->a[iField].pExpr = 0; 426 assert( pOrigLhs->a[iField].pExpr!=0 ); 427 pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr); 428 pOrigLhs->a[iField].pExpr = 0; 429 } 430 } 431 sqlite3ExprListDelete(db, pOrigRhs); 432 sqlite3ExprListDelete(db, pOrigLhs); 433 pNew->pLeft->x.pList = pLhs; 434 pNew->x.pSelect->pEList = pRhs; 435 if( pLhs && pLhs->nExpr==1 ){ 436 /* Take care here not to generate a TK_VECTOR containing only a 437 ** single value. Since the parser never creates such a vector, some 438 ** of the subroutines do not handle this case. */ 439 Expr *p = pLhs->a[0].pExpr; 440 pLhs->a[0].pExpr = 0; 441 sqlite3ExprDelete(db, pNew->pLeft); 442 pNew->pLeft = p; 443 } 444 pSelect = pNew->x.pSelect; 445 if( pSelect->pOrderBy ){ 446 /* If the SELECT statement has an ORDER BY clause, zero the 447 ** iOrderByCol variables. These are set to non-zero when an 448 ** ORDER BY term exactly matches one of the terms of the 449 ** result-set. Since the result-set of the SELECT statement may 450 ** have been modified or reordered, these variables are no longer 451 ** set correctly. Since setting them is just an optimization, 452 ** it's easiest just to zero them here. */ 453 ExprList *pOrderBy = pSelect->pOrderBy; 454 for(i=0; i<pOrderBy->nExpr; i++){ 455 pOrderBy->a[i].u.x.iOrderByCol = 0; 456 } 457 } 458 459 #if 0 460 printf("For indexing, change the IN expr:\n"); 461 sqlite3TreeViewExpr(0, pX, 0); 462 printf("Into:\n"); 463 sqlite3TreeViewExpr(0, pNew, 0); 464 #endif 465 } 466 return pNew; 467 } 468 469 470 /* 471 ** Generate code for a single equality term of the WHERE clause. An equality 472 ** term can be either X=expr or X IN (...). pTerm is the term to be 473 ** coded. 474 ** 475 ** The current value for the constraint is left in a register, the index 476 ** of which is returned. An attempt is made store the result in iTarget but 477 ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the 478 ** constraint is a TK_EQ or TK_IS, then the current value might be left in 479 ** some other register and it is the caller's responsibility to compensate. 480 ** 481 ** For a constraint of the form X=expr, the expression is evaluated in 482 ** straight-line code. For constraints of the form X IN (...) 483 ** this routine sets up a loop that will iterate over all values of X. 484 */ 485 static int codeEqualityTerm( 486 Parse *pParse, /* The parsing context */ 487 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ 488 WhereLevel *pLevel, /* The level of the FROM clause we are working on */ 489 int iEq, /* Index of the equality term within this level */ 490 int bRev, /* True for reverse-order IN operations */ 491 int iTarget /* Attempt to leave results in this register */ 492 ){ 493 Expr *pX = pTerm->pExpr; 494 Vdbe *v = pParse->pVdbe; 495 int iReg; /* Register holding results */ 496 497 assert( pLevel->pWLoop->aLTerm[iEq]==pTerm ); 498 assert( iTarget>0 ); 499 if( pX->op==TK_EQ || pX->op==TK_IS ){ 500 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); 501 }else if( pX->op==TK_ISNULL ){ 502 iReg = iTarget; 503 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); 504 #ifndef SQLITE_OMIT_SUBQUERY 505 }else{ 506 int eType = IN_INDEX_NOOP; 507 int iTab; 508 struct InLoop *pIn; 509 WhereLoop *pLoop = pLevel->pWLoop; 510 int i; 511 int nEq = 0; 512 int *aiMap = 0; 513 514 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 515 && pLoop->u.btree.pIndex!=0 516 && pLoop->u.btree.pIndex->aSortOrder[iEq] 517 ){ 518 testcase( iEq==0 ); 519 testcase( bRev ); 520 bRev = !bRev; 521 } 522 assert( pX->op==TK_IN ); 523 iReg = iTarget; 524 525 for(i=0; i<iEq; i++){ 526 if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){ 527 disableTerm(pLevel, pTerm); 528 return iTarget; 529 } 530 } 531 for(i=iEq;i<pLoop->nLTerm; i++){ 532 assert( pLoop->aLTerm[i]!=0 ); 533 if( pLoop->aLTerm[i]->pExpr==pX ) nEq++; 534 } 535 536 iTab = 0; 537 if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){ 538 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab); 539 }else{ 540 sqlite3 *db = pParse->db; 541 pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX); 542 543 if( !db->mallocFailed ){ 544 aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq); 545 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab); 546 pTerm->pExpr->iTable = iTab; 547 } 548 sqlite3ExprDelete(db, pX); 549 pX = pTerm->pExpr; 550 } 551 552 if( eType==IN_INDEX_INDEX_DESC ){ 553 testcase( bRev ); 554 bRev = !bRev; 555 } 556 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); 557 VdbeCoverageIf(v, bRev); 558 VdbeCoverageIf(v, !bRev); 559 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); 560 561 pLoop->wsFlags |= WHERE_IN_ABLE; 562 if( pLevel->u.in.nIn==0 ){ 563 pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); 564 } 565 if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){ 566 pLoop->wsFlags |= WHERE_IN_EARLYOUT; 567 } 568 569 i = pLevel->u.in.nIn; 570 pLevel->u.in.nIn += nEq; 571 pLevel->u.in.aInLoop = 572 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, 573 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); 574 pIn = pLevel->u.in.aInLoop; 575 if( pIn ){ 576 int iMap = 0; /* Index in aiMap[] */ 577 pIn += i; 578 for(i=iEq;i<pLoop->nLTerm; i++){ 579 if( pLoop->aLTerm[i]->pExpr==pX ){ 580 int iOut = iReg + i - iEq; 581 if( eType==IN_INDEX_ROWID ){ 582 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut); 583 }else{ 584 int iCol = aiMap ? aiMap[iMap++] : 0; 585 pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut); 586 } 587 sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v); 588 if( i==iEq ){ 589 pIn->iCur = iTab; 590 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next; 591 if( iEq>0 ){ 592 pIn->iBase = iReg - i; 593 pIn->nPrefix = i; 594 }else{ 595 pIn->nPrefix = 0; 596 } 597 }else{ 598 pIn->eEndLoopOp = OP_Noop; 599 } 600 pIn++; 601 } 602 } 603 testcase( iEq>0 604 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 605 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ); 606 if( iEq>0 607 && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0 608 ){ 609 sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq); 610 } 611 }else{ 612 pLevel->u.in.nIn = 0; 613 } 614 sqlite3DbFree(pParse->db, aiMap); 615 #endif 616 } 617 disableTerm(pLevel, pTerm); 618 return iReg; 619 } 620 621 /* 622 ** Generate code that will evaluate all == and IN constraints for an 623 ** index scan. 624 ** 625 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). 626 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 627 ** The index has as many as three equality constraints, but in this 628 ** example, the third "c" value is an inequality. So only two 629 ** constraints are coded. This routine will generate code to evaluate 630 ** a==5 and b IN (1,2,3). The current values for a and b will be stored 631 ** in consecutive registers and the index of the first register is returned. 632 ** 633 ** In the example above nEq==2. But this subroutine works for any value 634 ** of nEq including 0. If nEq==0, this routine is nearly a no-op. 635 ** The only thing it does is allocate the pLevel->iMem memory cell and 636 ** compute the affinity string. 637 ** 638 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints 639 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is 640 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that 641 ** occurs after the nEq quality constraints. 642 ** 643 ** This routine allocates a range of nEq+nExtraReg memory cells and returns 644 ** the index of the first memory cell in that range. The code that 645 ** calls this routine will use that memory range to store keys for 646 ** start and termination conditions of the loop. 647 ** key value of the loop. If one or more IN operators appear, then 648 ** this routine allocates an additional nEq memory cells for internal 649 ** use. 650 ** 651 ** Before returning, *pzAff is set to point to a buffer containing a 652 ** copy of the column affinity string of the index allocated using 653 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated 654 ** with equality constraints that use BLOB or NONE affinity are set to 655 ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: 656 ** 657 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); 658 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; 659 ** 660 ** In the example above, the index on t1(a) has TEXT affinity. But since 661 ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, 662 ** no conversion should be attempted before using a t2.b value as part of 663 ** a key to search the index. Hence the first byte in the returned affinity 664 ** string in this example would be set to SQLITE_AFF_BLOB. 665 */ 666 static int codeAllEqualityTerms( 667 Parse *pParse, /* Parsing context */ 668 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ 669 int bRev, /* Reverse the order of IN operators */ 670 int nExtraReg, /* Number of extra registers to allocate */ 671 char **pzAff /* OUT: Set to point to affinity string */ 672 ){ 673 u16 nEq; /* The number of == or IN constraints to code */ 674 u16 nSkip; /* Number of left-most columns to skip */ 675 Vdbe *v = pParse->pVdbe; /* The vm under construction */ 676 Index *pIdx; /* The index being used for this loop */ 677 WhereTerm *pTerm; /* A single constraint term */ 678 WhereLoop *pLoop; /* The WhereLoop object */ 679 int j; /* Loop counter */ 680 int regBase; /* Base register */ 681 int nReg; /* Number of registers to allocate */ 682 char *zAff; /* Affinity string to return */ 683 684 /* This module is only called on query plans that use an index. */ 685 pLoop = pLevel->pWLoop; 686 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); 687 nEq = pLoop->u.btree.nEq; 688 nSkip = pLoop->nSkip; 689 pIdx = pLoop->u.btree.pIndex; 690 assert( pIdx!=0 ); 691 692 /* Figure out how many memory cells we will need then allocate them. 693 */ 694 regBase = pParse->nMem + 1; 695 nReg = pLoop->u.btree.nEq + nExtraReg; 696 pParse->nMem += nReg; 697 698 zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); 699 assert( zAff!=0 || pParse->db->mallocFailed ); 700 701 if( nSkip ){ 702 int iIdxCur = pLevel->iIdxCur; 703 sqlite3VdbeAddOp3(v, OP_Null, 0, regBase, regBase+nSkip-1); 704 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); 705 VdbeCoverageIf(v, bRev==0); 706 VdbeCoverageIf(v, bRev!=0); 707 VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); 708 j = sqlite3VdbeAddOp0(v, OP_Goto); 709 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), 710 iIdxCur, 0, regBase, nSkip); 711 VdbeCoverageIf(v, bRev==0); 712 VdbeCoverageIf(v, bRev!=0); 713 sqlite3VdbeJumpHere(v, j); 714 for(j=0; j<nSkip; j++){ 715 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); 716 testcase( pIdx->aiColumn[j]==XN_EXPR ); 717 VdbeComment((v, "%s", explainIndexColumnName(pIdx, j))); 718 } 719 } 720 721 /* Evaluate the equality constraints 722 */ 723 assert( zAff==0 || (int)strlen(zAff)>=nEq ); 724 for(j=nSkip; j<nEq; j++){ 725 int r1; 726 pTerm = pLoop->aLTerm[j]; 727 assert( pTerm!=0 ); 728 /* The following testcase is true for indices with redundant columns. 729 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ 730 testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); 731 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 732 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); 733 if( r1!=regBase+j ){ 734 if( nReg==1 ){ 735 sqlite3ReleaseTempReg(pParse, regBase); 736 regBase = r1; 737 }else{ 738 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); 739 } 740 } 741 if( pTerm->eOperator & WO_IN ){ 742 if( pTerm->pExpr->flags & EP_xIsSelect ){ 743 /* No affinity ever needs to be (or should be) applied to a value 744 ** from the RHS of an "? IN (SELECT ...)" expression. The 745 ** sqlite3FindInIndex() routine has already ensured that the 746 ** affinity of the comparison has been applied to the value. */ 747 if( zAff ) zAff[j] = SQLITE_AFF_BLOB; 748 } 749 }else if( (pTerm->eOperator & WO_ISNULL)==0 ){ 750 Expr *pRight = pTerm->pExpr->pRight; 751 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ 752 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); 753 VdbeCoverage(v); 754 } 755 if( pParse->db->mallocFailed==0 ){ 756 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ 757 zAff[j] = SQLITE_AFF_BLOB; 758 } 759 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ 760 zAff[j] = SQLITE_AFF_BLOB; 761 } 762 } 763 } 764 } 765 *pzAff = zAff; 766 return regBase; 767 } 768 769 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 770 /* 771 ** If the most recently coded instruction is a constant range constraint 772 ** (a string literal) that originated from the LIKE optimization, then 773 ** set P3 and P5 on the OP_String opcode so that the string will be cast 774 ** to a BLOB at appropriate times. 775 ** 776 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range 777 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range 778 ** scan loop run twice, once for strings and a second time for BLOBs. 779 ** The OP_String opcodes on the second pass convert the upper and lower 780 ** bound string constants to blobs. This routine makes the necessary changes 781 ** to the OP_String opcodes for that to happen. 782 ** 783 ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then 784 ** only the one pass through the string space is required, so this routine 785 ** becomes a no-op. 786 */ 787 static void whereLikeOptimizationStringFixup( 788 Vdbe *v, /* prepared statement under construction */ 789 WhereLevel *pLevel, /* The loop that contains the LIKE operator */ 790 WhereTerm *pTerm /* The upper or lower bound just coded */ 791 ){ 792 if( pTerm->wtFlags & TERM_LIKEOPT ){ 793 VdbeOp *pOp; 794 assert( pLevel->iLikeRepCntr>0 ); 795 pOp = sqlite3VdbeGetOp(v, -1); 796 assert( pOp!=0 ); 797 assert( pOp->opcode==OP_String8 798 || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); 799 pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */ 800 pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */ 801 } 802 } 803 #else 804 # define whereLikeOptimizationStringFixup(A,B,C) 805 #endif 806 807 #ifdef SQLITE_ENABLE_CURSOR_HINTS 808 /* 809 ** Information is passed from codeCursorHint() down to individual nodes of 810 ** the expression tree (by sqlite3WalkExpr()) using an instance of this 811 ** structure. 812 */ 813 struct CCurHint { 814 int iTabCur; /* Cursor for the main table */ 815 int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */ 816 Index *pIdx; /* The index used to access the table */ 817 }; 818 819 /* 820 ** This function is called for every node of an expression that is a candidate 821 ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference 822 ** the table CCurHint.iTabCur, verify that the same column can be 823 ** accessed through the index. If it cannot, then set pWalker->eCode to 1. 824 */ 825 static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){ 826 struct CCurHint *pHint = pWalker->u.pCCurHint; 827 assert( pHint->pIdx!=0 ); 828 if( pExpr->op==TK_COLUMN 829 && pExpr->iTable==pHint->iTabCur 830 && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0 831 ){ 832 pWalker->eCode = 1; 833 } 834 return WRC_Continue; 835 } 836 837 /* 838 ** Test whether or not expression pExpr, which was part of a WHERE clause, 839 ** should be included in the cursor-hint for a table that is on the rhs 840 ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the 841 ** expression is not suitable. 842 ** 843 ** An expression is unsuitable if it might evaluate to non NULL even if 844 ** a TK_COLUMN node that does affect the value of the expression is set 845 ** to NULL. For example: 846 ** 847 ** col IS NULL 848 ** col IS NOT NULL 849 ** coalesce(col, 1) 850 ** CASE WHEN col THEN 0 ELSE 1 END 851 */ 852 static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){ 853 if( pExpr->op==TK_IS 854 || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT 855 || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE 856 ){ 857 pWalker->eCode = 1; 858 }else if( pExpr->op==TK_FUNCTION ){ 859 int d1; 860 char d2[4]; 861 if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){ 862 pWalker->eCode = 1; 863 } 864 } 865 866 return WRC_Continue; 867 } 868 869 870 /* 871 ** This function is called on every node of an expression tree used as an 872 ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN 873 ** that accesses any table other than the one identified by 874 ** CCurHint.iTabCur, then do the following: 875 ** 876 ** 1) allocate a register and code an OP_Column instruction to read 877 ** the specified column into the new register, and 878 ** 879 ** 2) transform the expression node to a TK_REGISTER node that reads 880 ** from the newly populated register. 881 ** 882 ** Also, if the node is a TK_COLUMN that does access the table idenified 883 ** by pCCurHint.iTabCur, and an index is being used (which we will 884 ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into 885 ** an access of the index rather than the original table. 886 */ 887 static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){ 888 int rc = WRC_Continue; 889 struct CCurHint *pHint = pWalker->u.pCCurHint; 890 if( pExpr->op==TK_COLUMN ){ 891 if( pExpr->iTable!=pHint->iTabCur ){ 892 int reg = ++pWalker->pParse->nMem; /* Register for column value */ 893 sqlite3ExprCode(pWalker->pParse, pExpr, reg); 894 pExpr->op = TK_REGISTER; 895 pExpr->iTable = reg; 896 }else if( pHint->pIdx!=0 ){ 897 pExpr->iTable = pHint->iIdxCur; 898 pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn); 899 assert( pExpr->iColumn>=0 ); 900 } 901 }else if( pExpr->op==TK_AGG_FUNCTION ){ 902 /* An aggregate function in the WHERE clause of a query means this must 903 ** be a correlated sub-query, and expression pExpr is an aggregate from 904 ** the parent context. Do not walk the function arguments in this case. 905 ** 906 ** todo: It should be possible to replace this node with a TK_REGISTER 907 ** expression, as the result of the expression must be stored in a 908 ** register at this point. The same holds for TK_AGG_COLUMN nodes. */ 909 rc = WRC_Prune; 910 } 911 return rc; 912 } 913 914 /* 915 ** Insert an OP_CursorHint instruction if it is appropriate to do so. 916 */ 917 static void codeCursorHint( 918 SrcItem *pTabItem, /* FROM clause item */ 919 WhereInfo *pWInfo, /* The where clause */ 920 WhereLevel *pLevel, /* Which loop to provide hints for */ 921 WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */ 922 ){ 923 Parse *pParse = pWInfo->pParse; 924 sqlite3 *db = pParse->db; 925 Vdbe *v = pParse->pVdbe; 926 Expr *pExpr = 0; 927 WhereLoop *pLoop = pLevel->pWLoop; 928 int iCur; 929 WhereClause *pWC; 930 WhereTerm *pTerm; 931 int i, j; 932 struct CCurHint sHint; 933 Walker sWalker; 934 935 if( OptimizationDisabled(db, SQLITE_CursorHints) ) return; 936 iCur = pLevel->iTabCur; 937 assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor ); 938 sHint.iTabCur = iCur; 939 sHint.iIdxCur = pLevel->iIdxCur; 940 sHint.pIdx = pLoop->u.btree.pIndex; 941 memset(&sWalker, 0, sizeof(sWalker)); 942 sWalker.pParse = pParse; 943 sWalker.u.pCCurHint = &sHint; 944 pWC = &pWInfo->sWC; 945 for(i=0; i<pWC->nTerm; i++){ 946 pTerm = &pWC->a[i]; 947 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 948 if( pTerm->prereqAll & pLevel->notReady ) continue; 949 950 /* Any terms specified as part of the ON(...) clause for any LEFT 951 ** JOIN for which the current table is not the rhs are omitted 952 ** from the cursor-hint. 953 ** 954 ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms 955 ** that were specified as part of the WHERE clause must be excluded. 956 ** This is to address the following: 957 ** 958 ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL; 959 ** 960 ** Say there is a single row in t2 that matches (t1.a=t2.b), but its 961 ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is 962 ** pushed down to the cursor, this row is filtered out, causing 963 ** SQLite to synthesize a row of NULL values. Which does match the 964 ** WHERE clause, and so the query returns a row. Which is incorrect. 965 ** 966 ** For the same reason, WHERE terms such as: 967 ** 968 ** WHERE 1 = (t2.c IS NULL) 969 ** 970 ** are also excluded. See codeCursorHintIsOrFunction() for details. 971 */ 972 if( pTabItem->fg.jointype & JT_LEFT ){ 973 Expr *pExpr = pTerm->pExpr; 974 if( !ExprHasProperty(pExpr, EP_FromJoin) 975 || pExpr->iRightJoinTable!=pTabItem->iCursor 976 ){ 977 sWalker.eCode = 0; 978 sWalker.xExprCallback = codeCursorHintIsOrFunction; 979 sqlite3WalkExpr(&sWalker, pTerm->pExpr); 980 if( sWalker.eCode ) continue; 981 } 982 }else{ 983 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue; 984 } 985 986 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize 987 ** the cursor. These terms are not needed as hints for a pure range 988 ** scan (that has no == terms) so omit them. */ 989 if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){ 990 for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){} 991 if( j<pLoop->nLTerm ) continue; 992 } 993 994 /* No subqueries or non-deterministic functions allowed */ 995 if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue; 996 997 /* For an index scan, make sure referenced columns are actually in 998 ** the index. */ 999 if( sHint.pIdx!=0 ){ 1000 sWalker.eCode = 0; 1001 sWalker.xExprCallback = codeCursorHintCheckExpr; 1002 sqlite3WalkExpr(&sWalker, pTerm->pExpr); 1003 if( sWalker.eCode ) continue; 1004 } 1005 1006 /* If we survive all prior tests, that means this term is worth hinting */ 1007 pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0)); 1008 } 1009 if( pExpr!=0 ){ 1010 sWalker.xExprCallback = codeCursorHintFixExpr; 1011 sqlite3WalkExpr(&sWalker, pExpr); 1012 sqlite3VdbeAddOp4(v, OP_CursorHint, 1013 (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0, 1014 (const char*)pExpr, P4_EXPR); 1015 } 1016 } 1017 #else 1018 # define codeCursorHint(A,B,C,D) /* No-op */ 1019 #endif /* SQLITE_ENABLE_CURSOR_HINTS */ 1020 1021 /* 1022 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains 1023 ** a rowid value just read from cursor iIdxCur, open on index pIdx. This 1024 ** function generates code to do a deferred seek of cursor iCur to the 1025 ** rowid stored in register iRowid. 1026 ** 1027 ** Normally, this is just: 1028 ** 1029 ** OP_DeferredSeek $iCur $iRowid 1030 ** 1031 ** However, if the scan currently being coded is a branch of an OR-loop and 1032 ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek 1033 ** is set to iIdxCur and P4 is set to point to an array of integers 1034 ** containing one entry for each column of the table cursor iCur is open 1035 ** on. For each table column, if the column is the i'th column of the 1036 ** index, then the corresponding array entry is set to (i+1). If the column 1037 ** does not appear in the index at all, the array entry is set to 0. 1038 */ 1039 static void codeDeferredSeek( 1040 WhereInfo *pWInfo, /* Where clause context */ 1041 Index *pIdx, /* Index scan is using */ 1042 int iCur, /* Cursor for IPK b-tree */ 1043 int iIdxCur /* Index cursor */ 1044 ){ 1045 Parse *pParse = pWInfo->pParse; /* Parse context */ 1046 Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */ 1047 1048 assert( iIdxCur>0 ); 1049 assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 ); 1050 1051 pWInfo->bDeferredSeek = 1; 1052 sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur); 1053 if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) 1054 && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask) 1055 ){ 1056 int i; 1057 Table *pTab = pIdx->pTable; 1058 u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1)); 1059 if( ai ){ 1060 ai[0] = pTab->nCol; 1061 for(i=0; i<pIdx->nColumn-1; i++){ 1062 int x1, x2; 1063 assert( pIdx->aiColumn[i]<pTab->nCol ); 1064 x1 = pIdx->aiColumn[i]; 1065 x2 = sqlite3TableColumnToStorage(pTab, x1); 1066 testcase( x1!=x2 ); 1067 if( x1>=0 ) ai[x2+1] = i+1; 1068 } 1069 sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY); 1070 } 1071 } 1072 } 1073 1074 /* 1075 ** If the expression passed as the second argument is a vector, generate 1076 ** code to write the first nReg elements of the vector into an array 1077 ** of registers starting with iReg. 1078 ** 1079 ** If the expression is not a vector, then nReg must be passed 1. In 1080 ** this case, generate code to evaluate the expression and leave the 1081 ** result in register iReg. 1082 */ 1083 static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){ 1084 assert( nReg>0 ); 1085 if( p && sqlite3ExprIsVector(p) ){ 1086 #ifndef SQLITE_OMIT_SUBQUERY 1087 if( (p->flags & EP_xIsSelect) ){ 1088 Vdbe *v = pParse->pVdbe; 1089 int iSelect; 1090 assert( p->op==TK_SELECT ); 1091 iSelect = sqlite3CodeSubselect(pParse, p); 1092 sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1); 1093 }else 1094 #endif 1095 { 1096 int i; 1097 ExprList *pList = p->x.pList; 1098 assert( nReg<=pList->nExpr ); 1099 for(i=0; i<nReg; i++){ 1100 sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i); 1101 } 1102 } 1103 }else{ 1104 assert( nReg==1 ); 1105 sqlite3ExprCode(pParse, p, iReg); 1106 } 1107 } 1108 1109 /* An instance of the IdxExprTrans object carries information about a 1110 ** mapping from an expression on table columns into a column in an index 1111 ** down through the Walker. 1112 */ 1113 typedef struct IdxExprTrans { 1114 Expr *pIdxExpr; /* The index expression */ 1115 int iTabCur; /* The cursor of the corresponding table */ 1116 int iIdxCur; /* The cursor for the index */ 1117 int iIdxCol; /* The column for the index */ 1118 int iTabCol; /* The column for the table */ 1119 WhereInfo *pWInfo; /* Complete WHERE clause information */ 1120 sqlite3 *db; /* Database connection (for malloc()) */ 1121 } IdxExprTrans; 1122 1123 /* 1124 ** Preserve pExpr on the WhereETrans list of the WhereInfo. 1125 */ 1126 static void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){ 1127 WhereExprMod *pNew; 1128 pNew = sqlite3DbMallocRaw(pTrans->db, sizeof(*pNew)); 1129 if( pNew==0 ) return; 1130 pNew->pNext = pTrans->pWInfo->pExprMods; 1131 pTrans->pWInfo->pExprMods = pNew; 1132 pNew->pExpr = pExpr; 1133 memcpy(&pNew->orig, pExpr, sizeof(*pExpr)); 1134 } 1135 1136 /* The walker node callback used to transform matching expressions into 1137 ** a reference to an index column for an index on an expression. 1138 ** 1139 ** If pExpr matches, then transform it into a reference to the index column 1140 ** that contains the value of pExpr. 1141 */ 1142 static int whereIndexExprTransNode(Walker *p, Expr *pExpr){ 1143 IdxExprTrans *pX = p->u.pIdxTrans; 1144 if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){ 1145 preserveExpr(pX, pExpr); 1146 pExpr->affExpr = sqlite3ExprAffinity(pExpr); 1147 pExpr->op = TK_COLUMN; 1148 pExpr->iTable = pX->iIdxCur; 1149 pExpr->iColumn = pX->iIdxCol; 1150 pExpr->y.pTab = 0; 1151 testcase( ExprHasProperty(pExpr, EP_Skip) ); 1152 testcase( ExprHasProperty(pExpr, EP_Unlikely) ); 1153 ExprClearProperty(pExpr, EP_Skip|EP_Unlikely); 1154 return WRC_Prune; 1155 }else{ 1156 return WRC_Continue; 1157 } 1158 } 1159 1160 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1161 /* A walker node callback that translates a column reference to a table 1162 ** into a corresponding column reference of an index. 1163 */ 1164 static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){ 1165 if( pExpr->op==TK_COLUMN ){ 1166 IdxExprTrans *pX = p->u.pIdxTrans; 1167 if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){ 1168 assert( pExpr->y.pTab!=0 ); 1169 preserveExpr(pX, pExpr); 1170 pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn); 1171 pExpr->iTable = pX->iIdxCur; 1172 pExpr->iColumn = pX->iIdxCol; 1173 pExpr->y.pTab = 0; 1174 } 1175 } 1176 return WRC_Continue; 1177 } 1178 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 1179 1180 /* 1181 ** For an indexes on expression X, locate every instance of expression X 1182 ** in pExpr and change that subexpression into a reference to the appropriate 1183 ** column of the index. 1184 ** 1185 ** 2019-10-24: Updated to also translate references to a VIRTUAL column in 1186 ** the table into references to the corresponding (stored) column of the 1187 ** index. 1188 */ 1189 static void whereIndexExprTrans( 1190 Index *pIdx, /* The Index */ 1191 int iTabCur, /* Cursor of the table that is being indexed */ 1192 int iIdxCur, /* Cursor of the index itself */ 1193 WhereInfo *pWInfo /* Transform expressions in this WHERE clause */ 1194 ){ 1195 int iIdxCol; /* Column number of the index */ 1196 ExprList *aColExpr; /* Expressions that are indexed */ 1197 Table *pTab; 1198 Walker w; 1199 IdxExprTrans x; 1200 aColExpr = pIdx->aColExpr; 1201 if( aColExpr==0 && !pIdx->bHasVCol ){ 1202 /* The index does not reference any expressions or virtual columns 1203 ** so no translations are needed. */ 1204 return; 1205 } 1206 pTab = pIdx->pTable; 1207 memset(&w, 0, sizeof(w)); 1208 w.u.pIdxTrans = &x; 1209 x.iTabCur = iTabCur; 1210 x.iIdxCur = iIdxCur; 1211 x.pWInfo = pWInfo; 1212 x.db = pWInfo->pParse->db; 1213 for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){ 1214 i16 iRef = pIdx->aiColumn[iIdxCol]; 1215 if( iRef==XN_EXPR ){ 1216 assert( aColExpr->a[iIdxCol].pExpr!=0 ); 1217 x.pIdxExpr = aColExpr->a[iIdxCol].pExpr; 1218 if( sqlite3ExprIsConstant(x.pIdxExpr) ) continue; 1219 w.xExprCallback = whereIndexExprTransNode; 1220 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1221 }else if( iRef>=0 1222 && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0 1223 && (pTab->aCol[iRef].zColl==0 1224 || sqlite3StrICmp(pTab->aCol[iRef].zColl, sqlite3StrBINARY)==0) 1225 ){ 1226 /* Check to see if there are direct references to generated columns 1227 ** that are contained in the index. Pulling the generated column 1228 ** out of the index is an optimization only - the main table is always 1229 ** available if the index cannot be used. To avoid unnecessary 1230 ** complication, omit this optimization if the collating sequence for 1231 ** the column is non-standard */ 1232 x.iTabCol = iRef; 1233 w.xExprCallback = whereIndexExprTransColumn; 1234 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 1235 }else{ 1236 continue; 1237 } 1238 x.iIdxCol = iIdxCol; 1239 sqlite3WalkExpr(&w, pWInfo->pWhere); 1240 sqlite3WalkExprList(&w, pWInfo->pOrderBy); 1241 sqlite3WalkExprList(&w, pWInfo->pResultSet); 1242 } 1243 } 1244 1245 /* 1246 ** The pTruth expression is always true because it is the WHERE clause 1247 ** a partial index that is driving a query loop. Look through all of the 1248 ** WHERE clause terms on the query, and if any of those terms must be 1249 ** true because pTruth is true, then mark those WHERE clause terms as 1250 ** coded. 1251 */ 1252 static void whereApplyPartialIndexConstraints( 1253 Expr *pTruth, 1254 int iTabCur, 1255 WhereClause *pWC 1256 ){ 1257 int i; 1258 WhereTerm *pTerm; 1259 while( pTruth->op==TK_AND ){ 1260 whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC); 1261 pTruth = pTruth->pRight; 1262 } 1263 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ 1264 Expr *pExpr; 1265 if( pTerm->wtFlags & TERM_CODED ) continue; 1266 pExpr = pTerm->pExpr; 1267 if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){ 1268 pTerm->wtFlags |= TERM_CODED; 1269 } 1270 } 1271 } 1272 1273 /* 1274 ** Generate code for the start of the iLevel-th loop in the WHERE clause 1275 ** implementation described by pWInfo. 1276 */ 1277 Bitmask sqlite3WhereCodeOneLoopStart( 1278 Parse *pParse, /* Parsing context */ 1279 Vdbe *v, /* Prepared statement under construction */ 1280 WhereInfo *pWInfo, /* Complete information about the WHERE clause */ 1281 int iLevel, /* Which level of pWInfo->a[] should be coded */ 1282 WhereLevel *pLevel, /* The current level pointer */ 1283 Bitmask notReady /* Which tables are currently available */ 1284 ){ 1285 int j, k; /* Loop counters */ 1286 int iCur; /* The VDBE cursor for the table */ 1287 int addrNxt; /* Where to jump to continue with the next IN case */ 1288 int bRev; /* True if we need to scan in reverse order */ 1289 WhereLoop *pLoop; /* The WhereLoop object being coded */ 1290 WhereClause *pWC; /* Decomposition of the entire WHERE clause */ 1291 WhereTerm *pTerm; /* A WHERE clause term */ 1292 sqlite3 *db; /* Database connection */ 1293 SrcItem *pTabItem; /* FROM clause term being coded */ 1294 int addrBrk; /* Jump here to break out of the loop */ 1295 int addrHalt; /* addrBrk for the outermost loop */ 1296 int addrCont; /* Jump here to continue with next cycle */ 1297 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ 1298 int iReleaseReg = 0; /* Temp register to free before returning */ 1299 Index *pIdx = 0; /* Index used by loop (if any) */ 1300 int iLoop; /* Iteration of constraint generator loop */ 1301 1302 pWC = &pWInfo->sWC; 1303 db = pParse->db; 1304 pLoop = pLevel->pWLoop; 1305 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; 1306 iCur = pTabItem->iCursor; 1307 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); 1308 bRev = (pWInfo->revMask>>iLevel)&1; 1309 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); 1310 #if WHERETRACE_ENABLED /* 0x20800 */ 1311 if( sqlite3WhereTrace & 0x800 ){ 1312 sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n", 1313 iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom); 1314 sqlite3WhereLoopPrint(pLoop, pWC); 1315 } 1316 if( sqlite3WhereTrace & 0x20000 ){ 1317 if( iLevel==0 ){ 1318 sqlite3DebugPrintf("WHERE clause being coded:\n"); 1319 sqlite3TreeViewExpr(0, pWInfo->pWhere, 0); 1320 } 1321 sqlite3DebugPrintf("All WHERE-clause terms before coding:\n"); 1322 sqlite3WhereClausePrint(pWC); 1323 } 1324 #endif 1325 1326 /* Create labels for the "break" and "continue" instructions 1327 ** for the current loop. Jump to addrBrk to break out of a loop. 1328 ** Jump to cont to go immediately to the next iteration of the 1329 ** loop. 1330 ** 1331 ** When there is an IN operator, we also have a "addrNxt" label that 1332 ** means to continue with the next IN value combination. When 1333 ** there are no IN operators in the constraints, the "addrNxt" label 1334 ** is the same as "addrBrk". 1335 */ 1336 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse); 1337 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse); 1338 1339 /* If this is the right table of a LEFT OUTER JOIN, allocate and 1340 ** initialize a memory cell that records if this table matches any 1341 ** row of the left table of the join. 1342 */ 1343 assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE) 1344 || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0 1345 ); 1346 if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ 1347 pLevel->iLeftJoin = ++pParse->nMem; 1348 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); 1349 VdbeComment((v, "init LEFT JOIN no-match flag")); 1350 } 1351 1352 /* Compute a safe address to jump to if we discover that the table for 1353 ** this loop is empty and can never contribute content. */ 1354 for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){} 1355 addrHalt = pWInfo->a[j].addrBrk; 1356 1357 /* Special case of a FROM clause subquery implemented as a co-routine */ 1358 if( pTabItem->fg.viaCoroutine ){ 1359 int regYield = pTabItem->regReturn; 1360 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); 1361 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); 1362 VdbeCoverage(v); 1363 VdbeComment((v, "next row of %s", pTabItem->pTab->zName)); 1364 pLevel->op = OP_Goto; 1365 }else 1366 1367 #ifndef SQLITE_OMIT_VIRTUALTABLE 1368 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 1369 /* Case 1: The table is a virtual-table. Use the VFilter and VNext 1370 ** to access the data. 1371 */ 1372 int iReg; /* P3 Value for OP_VFilter */ 1373 int addrNotFound; 1374 int nConstraint = pLoop->nLTerm; 1375 int iIn; /* Counter for IN constraints */ 1376 1377 iReg = sqlite3GetTempRange(pParse, nConstraint+2); 1378 addrNotFound = pLevel->addrBrk; 1379 for(j=0; j<nConstraint; j++){ 1380 int iTarget = iReg+j+2; 1381 pTerm = pLoop->aLTerm[j]; 1382 if( NEVER(pTerm==0) ) continue; 1383 if( pTerm->eOperator & WO_IN ){ 1384 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); 1385 addrNotFound = pLevel->addrNxt; 1386 }else{ 1387 Expr *pRight = pTerm->pExpr->pRight; 1388 codeExprOrVector(pParse, pRight, iTarget, 1); 1389 } 1390 } 1391 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); 1392 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); 1393 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, 1394 pLoop->u.vtab.idxStr, 1395 pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC); 1396 VdbeCoverage(v); 1397 pLoop->u.vtab.needFree = 0; 1398 /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed 1399 ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */ 1400 if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0; 1401 pLevel->p1 = iCur; 1402 pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext; 1403 pLevel->p2 = sqlite3VdbeCurrentAddr(v); 1404 iIn = pLevel->u.in.nIn; 1405 for(j=nConstraint-1; j>=0; j--){ 1406 pTerm = pLoop->aLTerm[j]; 1407 if( (pTerm->eOperator & WO_IN)!=0 ) iIn--; 1408 if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){ 1409 disableTerm(pLevel, pTerm); 1410 }else if( (pTerm->eOperator & WO_IN)!=0 1411 && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1 1412 ){ 1413 Expr *pCompare; /* The comparison operator */ 1414 Expr *pRight; /* RHS of the comparison */ 1415 VdbeOp *pOp; /* Opcode to access the value of the IN constraint */ 1416 1417 /* Reload the constraint value into reg[iReg+j+2]. The same value 1418 ** was loaded into the same register prior to the OP_VFilter, but 1419 ** the xFilter implementation might have changed the datatype or 1420 ** encoding of the value in the register, so it *must* be reloaded. */ 1421 assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed ); 1422 if( !db->mallocFailed ){ 1423 assert( iIn>=0 && iIn<pLevel->u.in.nIn ); 1424 pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop); 1425 assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid ); 1426 assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 ); 1427 assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 ); 1428 testcase( pOp->opcode==OP_Rowid ); 1429 sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3); 1430 } 1431 1432 /* Generate code that will continue to the next row if 1433 ** the IN constraint is not satisfied */ 1434 pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0); 1435 assert( pCompare!=0 || db->mallocFailed ); 1436 if( pCompare ){ 1437 pCompare->pLeft = pTerm->pExpr->pLeft; 1438 pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0); 1439 if( pRight ){ 1440 pRight->iTable = iReg+j+2; 1441 sqlite3ExprIfFalse( 1442 pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL 1443 ); 1444 } 1445 pCompare->pLeft = 0; 1446 sqlite3ExprDelete(db, pCompare); 1447 } 1448 } 1449 } 1450 assert( iIn==0 || db->mallocFailed ); 1451 /* These registers need to be preserved in case there is an IN operator 1452 ** loop. So we could deallocate the registers here (and potentially 1453 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems 1454 ** simpler and safer to simply not reuse the registers. 1455 ** 1456 ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); 1457 */ 1458 }else 1459 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 1460 1461 if( (pLoop->wsFlags & WHERE_IPK)!=0 1462 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 1463 ){ 1464 /* Case 2: We can directly reference a single row using an 1465 ** equality comparison against the ROWID field. Or 1466 ** we reference multiple rows using a "rowid IN (...)" 1467 ** construct. 1468 */ 1469 assert( pLoop->u.btree.nEq==1 ); 1470 pTerm = pLoop->aLTerm[0]; 1471 assert( pTerm!=0 ); 1472 assert( pTerm->pExpr!=0 ); 1473 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 1474 iReleaseReg = ++pParse->nMem; 1475 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); 1476 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); 1477 addrNxt = pLevel->addrNxt; 1478 sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg); 1479 VdbeCoverage(v); 1480 pLevel->op = OP_Noop; 1481 if( (pTerm->prereqAll & pLevel->notReady)==0 ){ 1482 pTerm->wtFlags |= TERM_CODED; 1483 } 1484 }else if( (pLoop->wsFlags & WHERE_IPK)!=0 1485 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 1486 ){ 1487 /* Case 3: We have an inequality comparison against the ROWID field. 1488 */ 1489 int testOp = OP_Noop; 1490 int start; 1491 int memEndValue = 0; 1492 WhereTerm *pStart, *pEnd; 1493 1494 j = 0; 1495 pStart = pEnd = 0; 1496 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; 1497 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; 1498 assert( pStart!=0 || pEnd!=0 ); 1499 if( bRev ){ 1500 pTerm = pStart; 1501 pStart = pEnd; 1502 pEnd = pTerm; 1503 } 1504 codeCursorHint(pTabItem, pWInfo, pLevel, pEnd); 1505 if( pStart ){ 1506 Expr *pX; /* The expression that defines the start bound */ 1507 int r1, rTemp; /* Registers for holding the start boundary */ 1508 int op; /* Cursor seek operation */ 1509 1510 /* The following constant maps TK_xx codes into corresponding 1511 ** seek opcodes. It depends on a particular ordering of TK_xx 1512 */ 1513 const u8 aMoveOp[] = { 1514 /* TK_GT */ OP_SeekGT, 1515 /* TK_LE */ OP_SeekLE, 1516 /* TK_LT */ OP_SeekLT, 1517 /* TK_GE */ OP_SeekGE 1518 }; 1519 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ 1520 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ 1521 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ 1522 1523 assert( (pStart->wtFlags & TERM_VNULL)==0 ); 1524 testcase( pStart->wtFlags & TERM_VIRTUAL ); 1525 pX = pStart->pExpr; 1526 assert( pX!=0 ); 1527 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ 1528 if( sqlite3ExprIsVector(pX->pRight) ){ 1529 r1 = rTemp = sqlite3GetTempReg(pParse); 1530 codeExprOrVector(pParse, pX->pRight, r1, 1); 1531 testcase( pX->op==TK_GT ); 1532 testcase( pX->op==TK_GE ); 1533 testcase( pX->op==TK_LT ); 1534 testcase( pX->op==TK_LE ); 1535 op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1]; 1536 assert( pX->op!=TK_GT || op==OP_SeekGE ); 1537 assert( pX->op!=TK_GE || op==OP_SeekGE ); 1538 assert( pX->op!=TK_LT || op==OP_SeekLE ); 1539 assert( pX->op!=TK_LE || op==OP_SeekLE ); 1540 }else{ 1541 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); 1542 disableTerm(pLevel, pStart); 1543 op = aMoveOp[(pX->op - TK_GT)]; 1544 } 1545 sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1); 1546 VdbeComment((v, "pk")); 1547 VdbeCoverageIf(v, pX->op==TK_GT); 1548 VdbeCoverageIf(v, pX->op==TK_LE); 1549 VdbeCoverageIf(v, pX->op==TK_LT); 1550 VdbeCoverageIf(v, pX->op==TK_GE); 1551 sqlite3ReleaseTempReg(pParse, rTemp); 1552 }else{ 1553 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt); 1554 VdbeCoverageIf(v, bRev==0); 1555 VdbeCoverageIf(v, bRev!=0); 1556 } 1557 if( pEnd ){ 1558 Expr *pX; 1559 pX = pEnd->pExpr; 1560 assert( pX!=0 ); 1561 assert( (pEnd->wtFlags & TERM_VNULL)==0 ); 1562 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ 1563 testcase( pEnd->wtFlags & TERM_VIRTUAL ); 1564 memEndValue = ++pParse->nMem; 1565 codeExprOrVector(pParse, pX->pRight, memEndValue, 1); 1566 if( 0==sqlite3ExprIsVector(pX->pRight) 1567 && (pX->op==TK_LT || pX->op==TK_GT) 1568 ){ 1569 testOp = bRev ? OP_Le : OP_Ge; 1570 }else{ 1571 testOp = bRev ? OP_Lt : OP_Gt; 1572 } 1573 if( 0==sqlite3ExprIsVector(pX->pRight) ){ 1574 disableTerm(pLevel, pEnd); 1575 } 1576 } 1577 start = sqlite3VdbeCurrentAddr(v); 1578 pLevel->op = bRev ? OP_Prev : OP_Next; 1579 pLevel->p1 = iCur; 1580 pLevel->p2 = start; 1581 assert( pLevel->p5==0 ); 1582 if( testOp!=OP_Noop ){ 1583 iRowidReg = ++pParse->nMem; 1584 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); 1585 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); 1586 VdbeCoverageIf(v, testOp==OP_Le); 1587 VdbeCoverageIf(v, testOp==OP_Lt); 1588 VdbeCoverageIf(v, testOp==OP_Ge); 1589 VdbeCoverageIf(v, testOp==OP_Gt); 1590 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); 1591 } 1592 }else if( pLoop->wsFlags & WHERE_INDEXED ){ 1593 /* Case 4: A scan using an index. 1594 ** 1595 ** The WHERE clause may contain zero or more equality 1596 ** terms ("==" or "IN" operators) that refer to the N 1597 ** left-most columns of the index. It may also contain 1598 ** inequality constraints (>, <, >= or <=) on the indexed 1599 ** column that immediately follows the N equalities. Only 1600 ** the right-most column can be an inequality - the rest must 1601 ** use the "==" and "IN" operators. For example, if the 1602 ** index is on (x,y,z), then the following clauses are all 1603 ** optimized: 1604 ** 1605 ** x=5 1606 ** x=5 AND y=10 1607 ** x=5 AND y<10 1608 ** x=5 AND y>5 AND y<10 1609 ** x=5 AND y=5 AND z<=10 1610 ** 1611 ** The z<10 term of the following cannot be used, only 1612 ** the x=5 term: 1613 ** 1614 ** x=5 AND z<10 1615 ** 1616 ** N may be zero if there are inequality constraints. 1617 ** If there are no inequality constraints, then N is at 1618 ** least one. 1619 ** 1620 ** This case is also used when there are no WHERE clause 1621 ** constraints but an index is selected anyway, in order 1622 ** to force the output order to conform to an ORDER BY. 1623 */ 1624 static const u8 aStartOp[] = { 1625 0, 1626 0, 1627 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ 1628 OP_Last, /* 3: (!start_constraints && startEq && bRev) */ 1629 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ 1630 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ 1631 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ 1632 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ 1633 }; 1634 static const u8 aEndOp[] = { 1635 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ 1636 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ 1637 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ 1638 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ 1639 }; 1640 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ 1641 u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */ 1642 u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */ 1643 int regBase; /* Base register holding constraint values */ 1644 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ 1645 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ 1646 int startEq; /* True if range start uses ==, >= or <= */ 1647 int endEq; /* True if range end uses ==, >= or <= */ 1648 int start_constraints; /* Start of range is constrained */ 1649 int nConstraint; /* Number of constraint terms */ 1650 int iIdxCur; /* The VDBE cursor for the index */ 1651 int nExtraReg = 0; /* Number of extra registers needed */ 1652 int op; /* Instruction opcode */ 1653 char *zStartAff; /* Affinity for start of range constraint */ 1654 char *zEndAff = 0; /* Affinity for end of range constraint */ 1655 u8 bSeekPastNull = 0; /* True to seek past initial nulls */ 1656 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ 1657 int omitTable; /* True if we use the index only */ 1658 int regBignull = 0; /* big-null flag register */ 1659 int addrSeekScan = 0; /* Opcode of the OP_SeekScan, if any */ 1660 1661 pIdx = pLoop->u.btree.pIndex; 1662 iIdxCur = pLevel->iIdxCur; 1663 assert( nEq>=pLoop->nSkip ); 1664 1665 /* Find any inequality constraint terms for the start and end 1666 ** of the range. 1667 */ 1668 j = nEq; 1669 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ 1670 pRangeStart = pLoop->aLTerm[j++]; 1671 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm); 1672 /* Like optimization range constraints always occur in pairs */ 1673 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 1674 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); 1675 } 1676 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ 1677 pRangeEnd = pLoop->aLTerm[j++]; 1678 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop); 1679 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS 1680 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ 1681 assert( pRangeStart!=0 ); /* LIKE opt constraints */ 1682 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ 1683 pLevel->iLikeRepCntr = (u32)++pParse->nMem; 1684 sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr); 1685 VdbeComment((v, "LIKE loop counter")); 1686 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); 1687 /* iLikeRepCntr actually stores 2x the counter register number. The 1688 ** bottom bit indicates whether the search order is ASC or DESC. */ 1689 testcase( bRev ); 1690 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); 1691 assert( (bRev & ~1)==0 ); 1692 pLevel->iLikeRepCntr <<=1; 1693 pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC); 1694 } 1695 #endif 1696 if( pRangeStart==0 ){ 1697 j = pIdx->aiColumn[nEq]; 1698 if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){ 1699 bSeekPastNull = 1; 1700 } 1701 } 1702 } 1703 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); 1704 1705 /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses 1706 ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS 1707 ** FIRST). In both cases separate ordered scans are made of those 1708 ** index entries for which the column is null and for those for which 1709 ** it is not. For an ASC sort, the non-NULL entries are scanned first. 1710 ** For DESC, NULL entries are scanned first. 1711 */ 1712 if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0 1713 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0 1714 ){ 1715 assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 ); 1716 assert( pRangeEnd==0 && pRangeStart==0 ); 1717 testcase( pLoop->nSkip>0 ); 1718 nExtraReg = 1; 1719 bSeekPastNull = 1; 1720 pLevel->regBignull = regBignull = ++pParse->nMem; 1721 if( pLevel->iLeftJoin ){ 1722 sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull); 1723 } 1724 pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse); 1725 } 1726 1727 /* If we are doing a reverse order scan on an ascending index, or 1728 ** a forward order scan on a descending index, interchange the 1729 ** start and end terms (pRangeStart and pRangeEnd). 1730 */ 1731 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) 1732 || (bRev && pIdx->nKeyCol==nEq) 1733 ){ 1734 SWAP(WhereTerm *, pRangeEnd, pRangeStart); 1735 SWAP(u8, bSeekPastNull, bStopAtNull); 1736 SWAP(u8, nBtm, nTop); 1737 } 1738 1739 if( iLevel>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 ){ 1740 /* In case OP_SeekScan is used, ensure that the index cursor does not 1741 ** point to a valid row for the first iteration of this loop. */ 1742 sqlite3VdbeAddOp1(v, OP_NullRow, iIdxCur); 1743 } 1744 1745 /* Generate code to evaluate all constraint terms using == or IN 1746 ** and store the values of those terms in an array of registers 1747 ** starting at regBase. 1748 */ 1749 codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd); 1750 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); 1751 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); 1752 if( zStartAff && nTop ){ 1753 zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]); 1754 } 1755 addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt); 1756 1757 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); 1758 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); 1759 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); 1760 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); 1761 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); 1762 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); 1763 start_constraints = pRangeStart || nEq>0; 1764 1765 /* Seek the index cursor to the start of the range. */ 1766 nConstraint = nEq; 1767 if( pRangeStart ){ 1768 Expr *pRight = pRangeStart->pExpr->pRight; 1769 codeExprOrVector(pParse, pRight, regBase+nEq, nBtm); 1770 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); 1771 if( (pRangeStart->wtFlags & TERM_VNULL)==0 1772 && sqlite3ExprCanBeNull(pRight) 1773 ){ 1774 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 1775 VdbeCoverage(v); 1776 } 1777 if( zStartAff ){ 1778 updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]); 1779 } 1780 nConstraint += nBtm; 1781 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); 1782 if( sqlite3ExprIsVector(pRight)==0 ){ 1783 disableTerm(pLevel, pRangeStart); 1784 }else{ 1785 startEq = 1; 1786 } 1787 bSeekPastNull = 0; 1788 }else if( bSeekPastNull ){ 1789 startEq = 0; 1790 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 1791 start_constraints = 1; 1792 nConstraint++; 1793 }else if( regBignull ){ 1794 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 1795 start_constraints = 1; 1796 nConstraint++; 1797 } 1798 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); 1799 if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){ 1800 /* The skip-scan logic inside the call to codeAllEqualityConstraints() 1801 ** above has already left the cursor sitting on the correct row, 1802 ** so no further seeking is needed */ 1803 }else{ 1804 if( regBignull ){ 1805 sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull); 1806 VdbeComment((v, "NULL-scan pass ctr")); 1807 } 1808 1809 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; 1810 assert( op!=0 ); 1811 if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){ 1812 assert( regBignull==0 ); 1813 /* TUNING: The OP_SeekScan opcode seeks to reduce the number 1814 ** of expensive seek operations by replacing a single seek with 1815 ** 1 or more step operations. The question is, how many steps 1816 ** should we try before giving up and going with a seek. The cost 1817 ** of a seek is proportional to the logarithm of the of the number 1818 ** of entries in the tree, so basing the number of steps to try 1819 ** on the estimated number of rows in the btree seems like a good 1820 ** guess. */ 1821 addrSeekScan = sqlite3VdbeAddOp1(v, OP_SeekScan, 1822 (pIdx->aiRowLogEst[0]+9)/10); 1823 VdbeCoverage(v); 1824 } 1825 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 1826 VdbeCoverage(v); 1827 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); 1828 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); 1829 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); 1830 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); 1831 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); 1832 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); 1833 1834 assert( bSeekPastNull==0 || bStopAtNull==0 ); 1835 if( regBignull ){ 1836 assert( bSeekPastNull==1 || bStopAtNull==1 ); 1837 assert( bSeekPastNull==!bStopAtNull ); 1838 assert( bStopAtNull==startEq ); 1839 sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2); 1840 op = aStartOp[(nConstraint>1)*4 + 2 + bRev]; 1841 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, 1842 nConstraint-startEq); 1843 VdbeCoverage(v); 1844 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); 1845 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); 1846 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); 1847 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); 1848 assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE); 1849 } 1850 } 1851 1852 /* Load the value for the inequality constraint at the end of the 1853 ** range (if any). 1854 */ 1855 nConstraint = nEq; 1856 if( pRangeEnd ){ 1857 Expr *pRight = pRangeEnd->pExpr->pRight; 1858 codeExprOrVector(pParse, pRight, regBase+nEq, nTop); 1859 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); 1860 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 1861 && sqlite3ExprCanBeNull(pRight) 1862 ){ 1863 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 1864 VdbeCoverage(v); 1865 } 1866 if( zEndAff ){ 1867 updateRangeAffinityStr(pRight, nTop, zEndAff); 1868 codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff); 1869 }else{ 1870 assert( pParse->db->mallocFailed ); 1871 } 1872 nConstraint += nTop; 1873 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); 1874 1875 if( sqlite3ExprIsVector(pRight)==0 ){ 1876 disableTerm(pLevel, pRangeEnd); 1877 }else{ 1878 endEq = 1; 1879 } 1880 }else if( bStopAtNull ){ 1881 if( regBignull==0 ){ 1882 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 1883 endEq = 0; 1884 } 1885 nConstraint++; 1886 } 1887 sqlite3DbFree(db, zStartAff); 1888 sqlite3DbFree(db, zEndAff); 1889 1890 /* Top of the loop body */ 1891 pLevel->p2 = sqlite3VdbeCurrentAddr(v); 1892 1893 /* Check if the index cursor is past the end of the range. */ 1894 if( nConstraint ){ 1895 if( regBignull ){ 1896 /* Except, skip the end-of-range check while doing the NULL-scan */ 1897 sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3); 1898 VdbeComment((v, "If NULL-scan 2nd pass")); 1899 VdbeCoverage(v); 1900 } 1901 op = aEndOp[bRev*2 + endEq]; 1902 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 1903 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); 1904 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); 1905 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); 1906 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); 1907 if( addrSeekScan ) sqlite3VdbeJumpHere(v, addrSeekScan); 1908 } 1909 if( regBignull ){ 1910 /* During a NULL-scan, check to see if we have reached the end of 1911 ** the NULLs */ 1912 assert( bSeekPastNull==!bStopAtNull ); 1913 assert( bSeekPastNull+bStopAtNull==1 ); 1914 assert( nConstraint+bSeekPastNull>0 ); 1915 sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2); 1916 VdbeComment((v, "If NULL-scan 1st pass")); 1917 VdbeCoverage(v); 1918 op = aEndOp[bRev*2 + bSeekPastNull]; 1919 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, 1920 nConstraint+bSeekPastNull); 1921 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); 1922 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); 1923 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); 1924 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); 1925 } 1926 1927 if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){ 1928 sqlite3VdbeAddOp3(v, OP_SeekHit, iIdxCur, nEq, nEq); 1929 } 1930 1931 /* Seek the table cursor, if required */ 1932 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 1933 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0; 1934 if( omitTable ){ 1935 /* pIdx is a covering index. No need to access the main table. */ 1936 }else if( HasRowid(pIdx->pTable) ){ 1937 codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur); 1938 }else if( iCur!=iIdxCur ){ 1939 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); 1940 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); 1941 for(j=0; j<pPk->nKeyCol; j++){ 1942 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]); 1943 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); 1944 } 1945 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, 1946 iRowidReg, pPk->nKeyCol); VdbeCoverage(v); 1947 } 1948 1949 if( pLevel->iLeftJoin==0 ){ 1950 /* If pIdx is an index on one or more expressions, then look through 1951 ** all the expressions in pWInfo and try to transform matching expressions 1952 ** into reference to index columns. Also attempt to translate references 1953 ** to virtual columns in the table into references to (stored) columns 1954 ** of the index. 1955 ** 1956 ** Do not do this for the RHS of a LEFT JOIN. This is because the 1957 ** expression may be evaluated after OP_NullRow has been executed on 1958 ** the cursor. In this case it is important to do the full evaluation, 1959 ** as the result of the expression may not be NULL, even if all table 1960 ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a 1961 ** 1962 ** Also, do not do this when processing one index an a multi-index 1963 ** OR clause, since the transformation will become invalid once we 1964 ** move forward to the next index. 1965 ** https://sqlite.org/src/info/4e8e4857d32d401f 1966 */ 1967 if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){ 1968 whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo); 1969 } 1970 1971 /* If a partial index is driving the loop, try to eliminate WHERE clause 1972 ** terms from the query that must be true due to the WHERE clause of 1973 ** the partial index. 1974 ** 1975 ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work 1976 ** for a LEFT JOIN. 1977 */ 1978 if( pIdx->pPartIdxWhere ){ 1979 whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC); 1980 } 1981 }else{ 1982 testcase( pIdx->pPartIdxWhere ); 1983 /* The following assert() is not a requirement, merely an observation: 1984 ** The OR-optimization doesn't work for the right hand table of 1985 ** a LEFT JOIN: */ 1986 assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ); 1987 } 1988 1989 /* Record the instruction used to terminate the loop. */ 1990 if( pLoop->wsFlags & WHERE_ONEROW ){ 1991 pLevel->op = OP_Noop; 1992 }else if( bRev ){ 1993 pLevel->op = OP_Prev; 1994 }else{ 1995 pLevel->op = OP_Next; 1996 } 1997 pLevel->p1 = iIdxCur; 1998 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; 1999 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ 2000 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 2001 }else{ 2002 assert( pLevel->p5==0 ); 2003 } 2004 if( omitTable ) pIdx = 0; 2005 }else 2006 2007 #ifndef SQLITE_OMIT_OR_OPTIMIZATION 2008 if( pLoop->wsFlags & WHERE_MULTI_OR ){ 2009 /* Case 5: Two or more separately indexed terms connected by OR 2010 ** 2011 ** Example: 2012 ** 2013 ** CREATE TABLE t1(a,b,c,d); 2014 ** CREATE INDEX i1 ON t1(a); 2015 ** CREATE INDEX i2 ON t1(b); 2016 ** CREATE INDEX i3 ON t1(c); 2017 ** 2018 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) 2019 ** 2020 ** In the example, there are three indexed terms connected by OR. 2021 ** The top of the loop looks like this: 2022 ** 2023 ** Null 1 # Zero the rowset in reg 1 2024 ** 2025 ** Then, for each indexed term, the following. The arguments to 2026 ** RowSetTest are such that the rowid of the current row is inserted 2027 ** into the RowSet. If it is already present, control skips the 2028 ** Gosub opcode and jumps straight to the code generated by WhereEnd(). 2029 ** 2030 ** sqlite3WhereBegin(<term>) 2031 ** RowSetTest # Insert rowid into rowset 2032 ** Gosub 2 A 2033 ** sqlite3WhereEnd() 2034 ** 2035 ** Following the above, code to terminate the loop. Label A, the target 2036 ** of the Gosub above, jumps to the instruction right after the Goto. 2037 ** 2038 ** Null 1 # Zero the rowset in reg 1 2039 ** Goto B # The loop is finished. 2040 ** 2041 ** A: <loop body> # Return data, whatever. 2042 ** 2043 ** Return 2 # Jump back to the Gosub 2044 ** 2045 ** B: <after the loop> 2046 ** 2047 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then 2048 ** use an ephemeral index instead of a RowSet to record the primary 2049 ** keys of the rows we have already seen. 2050 ** 2051 */ 2052 WhereClause *pOrWc; /* The OR-clause broken out into subterms */ 2053 SrcList *pOrTab; /* Shortened table list or OR-clause generation */ 2054 Index *pCov = 0; /* Potential covering index (or NULL) */ 2055 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ 2056 2057 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ 2058 int regRowset = 0; /* Register for RowSet object */ 2059 int regRowid = 0; /* Register holding rowid */ 2060 int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */ 2061 int iRetInit; /* Address of regReturn init */ 2062 int untestedTerms = 0; /* Some terms not completely tested */ 2063 int ii; /* Loop counter */ 2064 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ 2065 Table *pTab = pTabItem->pTab; 2066 2067 pTerm = pLoop->aLTerm[0]; 2068 assert( pTerm!=0 ); 2069 assert( pTerm->eOperator & WO_OR ); 2070 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); 2071 pOrWc = &pTerm->u.pOrInfo->wc; 2072 pLevel->op = OP_Return; 2073 pLevel->p1 = regReturn; 2074 2075 /* Set up a new SrcList in pOrTab containing the table being scanned 2076 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. 2077 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). 2078 */ 2079 if( pWInfo->nLevel>1 ){ 2080 int nNotReady; /* The number of notReady tables */ 2081 SrcItem *origSrc; /* Original list of tables */ 2082 nNotReady = pWInfo->nLevel - iLevel - 1; 2083 pOrTab = sqlite3StackAllocRaw(db, 2084 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); 2085 if( pOrTab==0 ) return notReady; 2086 pOrTab->nAlloc = (u8)(nNotReady + 1); 2087 pOrTab->nSrc = pOrTab->nAlloc; 2088 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); 2089 origSrc = pWInfo->pTabList->a; 2090 for(k=1; k<=nNotReady; k++){ 2091 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); 2092 } 2093 }else{ 2094 pOrTab = pWInfo->pTabList; 2095 } 2096 2097 /* Initialize the rowset register to contain NULL. An SQL NULL is 2098 ** equivalent to an empty rowset. Or, create an ephemeral index 2099 ** capable of holding primary keys in the case of a WITHOUT ROWID. 2100 ** 2101 ** Also initialize regReturn to contain the address of the instruction 2102 ** immediately following the OP_Return at the bottom of the loop. This 2103 ** is required in a few obscure LEFT JOIN cases where control jumps 2104 ** over the top of the loop into the body of it. In this case the 2105 ** correct response for the end-of-loop code (the OP_Return) is to 2106 ** fall through to the next instruction, just as an OP_Next does if 2107 ** called on an uninitialized cursor. 2108 */ 2109 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 2110 if( HasRowid(pTab) ){ 2111 regRowset = ++pParse->nMem; 2112 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); 2113 }else{ 2114 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 2115 regRowset = pParse->nTab++; 2116 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); 2117 sqlite3VdbeSetP4KeyInfo(pParse, pPk); 2118 } 2119 regRowid = ++pParse->nMem; 2120 } 2121 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); 2122 2123 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y 2124 ** Then for every term xN, evaluate as the subexpression: xN AND z 2125 ** That way, terms in y that are factored into the disjunction will 2126 ** be picked up by the recursive calls to sqlite3WhereBegin() below. 2127 ** 2128 ** Actually, each subexpression is converted to "xN AND w" where w is 2129 ** the "interesting" terms of z - terms that did not originate in the 2130 ** ON or USING clause of a LEFT JOIN, and terms that are usable as 2131 ** indices. 2132 ** 2133 ** This optimization also only applies if the (x1 OR x2 OR ...) term 2134 ** is not contained in the ON clause of a LEFT JOIN. 2135 ** See ticket http://www.sqlite.org/src/info/f2369304e4 2136 */ 2137 if( pWC->nTerm>1 ){ 2138 int iTerm; 2139 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ 2140 Expr *pExpr = pWC->a[iTerm].pExpr; 2141 if( &pWC->a[iTerm] == pTerm ) continue; 2142 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); 2143 testcase( pWC->a[iTerm].wtFlags & TERM_CODED ); 2144 if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue; 2145 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; 2146 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); 2147 pExpr = sqlite3ExprDup(db, pExpr, 0); 2148 pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr); 2149 } 2150 if( pAndExpr ){ 2151 /* The extra 0x10000 bit on the opcode is masked off and does not 2152 ** become part of the new Expr.op. However, it does make the 2153 ** op==TK_AND comparison inside of sqlite3PExpr() false, and this 2154 ** prevents sqlite3PExpr() from implementing AND short-circuit 2155 ** optimization, which we do not want here. */ 2156 pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr); 2157 } 2158 } 2159 2160 /* Run a separate WHERE clause for each term of the OR clause. After 2161 ** eliminating duplicates from other WHERE clauses, the action for each 2162 ** sub-WHERE clause is to to invoke the main loop body as a subroutine. 2163 */ 2164 ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR")); 2165 for(ii=0; ii<pOrWc->nTerm; ii++){ 2166 WhereTerm *pOrTerm = &pOrWc->a[ii]; 2167 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ 2168 WhereInfo *pSubWInfo; /* Info for single OR-term scan */ 2169 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ 2170 int jmp1 = 0; /* Address of jump operation */ 2171 testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0 2172 && !ExprHasProperty(pOrExpr, EP_FromJoin) 2173 ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */ 2174 if( pAndExpr ){ 2175 pAndExpr->pLeft = pOrExpr; 2176 pOrExpr = pAndExpr; 2177 } 2178 /* Loop through table entries that match term pOrTerm. */ 2179 ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1)); 2180 WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); 2181 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 2182 WHERE_OR_SUBCLAUSE, iCovCur); 2183 assert( pSubWInfo || pParse->nErr || db->mallocFailed ); 2184 if( pSubWInfo ){ 2185 WhereLoop *pSubLoop; 2186 int addrExplain = sqlite3WhereExplainOneScan( 2187 pParse, pOrTab, &pSubWInfo->a[0], 0 2188 ); 2189 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); 2190 2191 /* This is the sub-WHERE clause body. First skip over 2192 ** duplicate rows from prior sub-WHERE clauses, and record the 2193 ** rowid (or PRIMARY KEY) for the current row so that the same 2194 ** row will be skipped in subsequent sub-WHERE clauses. 2195 */ 2196 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 2197 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); 2198 if( HasRowid(pTab) ){ 2199 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid); 2200 jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, 2201 regRowid, iSet); 2202 VdbeCoverage(v); 2203 }else{ 2204 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 2205 int nPk = pPk->nKeyCol; 2206 int iPk; 2207 int r; 2208 2209 /* Read the PK into an array of temp registers. */ 2210 r = sqlite3GetTempRange(pParse, nPk); 2211 for(iPk=0; iPk<nPk; iPk++){ 2212 int iCol = pPk->aiColumn[iPk]; 2213 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk); 2214 } 2215 2216 /* Check if the temp table already contains this key. If so, 2217 ** the row has already been included in the result set and 2218 ** can be ignored (by jumping past the Gosub below). Otherwise, 2219 ** insert the key into the temp table and proceed with processing 2220 ** the row. 2221 ** 2222 ** Use some of the same optimizations as OP_RowSetTest: If iSet 2223 ** is zero, assume that the key cannot already be present in 2224 ** the temp table. And if iSet is -1, assume that there is no 2225 ** need to insert the key into the temp table, as it will never 2226 ** be tested for. */ 2227 if( iSet ){ 2228 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); 2229 VdbeCoverage(v); 2230 } 2231 if( iSet>=0 ){ 2232 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); 2233 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid, 2234 r, nPk); 2235 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 2236 } 2237 2238 /* Release the array of temp registers */ 2239 sqlite3ReleaseTempRange(pParse, r, nPk); 2240 } 2241 } 2242 2243 /* Invoke the main loop body as a subroutine */ 2244 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); 2245 2246 /* Jump here (skipping the main loop body subroutine) if the 2247 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ 2248 if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1); 2249 2250 /* The pSubWInfo->untestedTerms flag means that this OR term 2251 ** contained one or more AND term from a notReady table. The 2252 ** terms from the notReady table could not be tested and will 2253 ** need to be tested later. 2254 */ 2255 if( pSubWInfo->untestedTerms ) untestedTerms = 1; 2256 2257 /* If all of the OR-connected terms are optimized using the same 2258 ** index, and the index is opened using the same cursor number 2259 ** by each call to sqlite3WhereBegin() made by this loop, it may 2260 ** be possible to use that index as a covering index. 2261 ** 2262 ** If the call to sqlite3WhereBegin() above resulted in a scan that 2263 ** uses an index, and this is either the first OR-connected term 2264 ** processed or the index is the same as that used by all previous 2265 ** terms, set pCov to the candidate covering index. Otherwise, set 2266 ** pCov to NULL to indicate that no candidate covering index will 2267 ** be available. 2268 */ 2269 pSubLoop = pSubWInfo->a[0].pWLoop; 2270 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); 2271 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 2272 && (ii==0 || pSubLoop->u.btree.pIndex==pCov) 2273 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) 2274 ){ 2275 assert( pSubWInfo->a[0].iIdxCur==iCovCur ); 2276 pCov = pSubLoop->u.btree.pIndex; 2277 }else{ 2278 pCov = 0; 2279 } 2280 if( sqlite3WhereUsesDeferredSeek(pSubWInfo) ){ 2281 pWInfo->bDeferredSeek = 1; 2282 } 2283 2284 /* Finish the loop through table entries that match term pOrTerm. */ 2285 sqlite3WhereEnd(pSubWInfo); 2286 ExplainQueryPlanPop(pParse); 2287 } 2288 } 2289 } 2290 ExplainQueryPlanPop(pParse); 2291 pLevel->u.pCovidx = pCov; 2292 if( pCov ) pLevel->iIdxCur = iCovCur; 2293 if( pAndExpr ){ 2294 pAndExpr->pLeft = 0; 2295 sqlite3ExprDelete(db, pAndExpr); 2296 } 2297 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); 2298 sqlite3VdbeGoto(v, pLevel->addrBrk); 2299 sqlite3VdbeResolveLabel(v, iLoopBody); 2300 2301 if( pWInfo->nLevel>1 ){ sqlite3StackFree(db, pOrTab); } 2302 if( !untestedTerms ) disableTerm(pLevel, pTerm); 2303 }else 2304 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 2305 2306 { 2307 /* Case 6: There is no usable index. We must do a complete 2308 ** scan of the entire table. 2309 */ 2310 static const u8 aStep[] = { OP_Next, OP_Prev }; 2311 static const u8 aStart[] = { OP_Rewind, OP_Last }; 2312 assert( bRev==0 || bRev==1 ); 2313 if( pTabItem->fg.isRecursive ){ 2314 /* Tables marked isRecursive have only a single row that is stored in 2315 ** a pseudo-cursor. No need to Rewind or Next such cursors. */ 2316 pLevel->op = OP_Noop; 2317 }else{ 2318 codeCursorHint(pTabItem, pWInfo, pLevel, 0); 2319 pLevel->op = aStep[bRev]; 2320 pLevel->p1 = iCur; 2321 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt); 2322 VdbeCoverageIf(v, bRev==0); 2323 VdbeCoverageIf(v, bRev!=0); 2324 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 2325 } 2326 } 2327 2328 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 2329 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); 2330 #endif 2331 2332 /* Insert code to test every subexpression that can be completely 2333 ** computed using the current set of tables. 2334 ** 2335 ** This loop may run between one and three times, depending on the 2336 ** constraints to be generated. The value of stack variable iLoop 2337 ** determines the constraints coded by each iteration, as follows: 2338 ** 2339 ** iLoop==1: Code only expressions that are entirely covered by pIdx. 2340 ** iLoop==2: Code remaining expressions that do not contain correlated 2341 ** sub-queries. 2342 ** iLoop==3: Code all remaining expressions. 2343 ** 2344 ** An effort is made to skip unnecessary iterations of the loop. 2345 */ 2346 iLoop = (pIdx ? 1 : 2); 2347 do{ 2348 int iNext = 0; /* Next value for iLoop */ 2349 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 2350 Expr *pE; 2351 int skipLikeAddr = 0; 2352 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 2353 testcase( pTerm->wtFlags & TERM_CODED ); 2354 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 2355 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 2356 testcase( pWInfo->untestedTerms==0 2357 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ); 2358 pWInfo->untestedTerms = 1; 2359 continue; 2360 } 2361 pE = pTerm->pExpr; 2362 assert( pE!=0 ); 2363 if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){ 2364 continue; 2365 } 2366 2367 if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){ 2368 iNext = 2; 2369 continue; 2370 } 2371 if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){ 2372 if( iNext==0 ) iNext = 3; 2373 continue; 2374 } 2375 2376 if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){ 2377 /* If the TERM_LIKECOND flag is set, that means that the range search 2378 ** is sufficient to guarantee that the LIKE operator is true, so we 2379 ** can skip the call to the like(A,B) function. But this only works 2380 ** for strings. So do not skip the call to the function on the pass 2381 ** that compares BLOBs. */ 2382 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS 2383 continue; 2384 #else 2385 u32 x = pLevel->iLikeRepCntr; 2386 if( x>0 ){ 2387 skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1)); 2388 VdbeCoverageIf(v, (x&1)==1); 2389 VdbeCoverageIf(v, (x&1)==0); 2390 } 2391 #endif 2392 } 2393 #ifdef WHERETRACE_ENABLED /* 0xffff */ 2394 if( sqlite3WhereTrace ){ 2395 VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d", 2396 pWC->nTerm-j, pTerm, iLoop)); 2397 } 2398 if( sqlite3WhereTrace & 0x800 ){ 2399 sqlite3DebugPrintf("Coding auxiliary constraint:\n"); 2400 sqlite3WhereTermPrint(pTerm, pWC->nTerm-j); 2401 } 2402 #endif 2403 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); 2404 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); 2405 pTerm->wtFlags |= TERM_CODED; 2406 } 2407 iLoop = iNext; 2408 }while( iLoop>0 ); 2409 2410 /* Insert code to test for implied constraints based on transitivity 2411 ** of the "==" operator. 2412 ** 2413 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" 2414 ** and we are coding the t1 loop and the t2 loop has not yet coded, 2415 ** then we cannot use the "t1.a=t2.b" constraint, but we can code 2416 ** the implied "t1.a=123" constraint. 2417 */ 2418 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 2419 Expr *pE, sEAlt; 2420 WhereTerm *pAlt; 2421 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 2422 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; 2423 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; 2424 if( pTerm->leftCursor!=iCur ) continue; 2425 if( pTabItem->fg.jointype & JT_LEFT ) continue; 2426 pE = pTerm->pExpr; 2427 #ifdef WHERETRACE_ENABLED /* 0x800 */ 2428 if( sqlite3WhereTrace & 0x800 ){ 2429 sqlite3DebugPrintf("Coding transitive constraint:\n"); 2430 sqlite3WhereTermPrint(pTerm, pWC->nTerm-j); 2431 } 2432 #endif 2433 assert( !ExprHasProperty(pE, EP_FromJoin) ); 2434 assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); 2435 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady, 2436 WO_EQ|WO_IN|WO_IS, 0); 2437 if( pAlt==0 ) continue; 2438 if( pAlt->wtFlags & (TERM_CODED) ) continue; 2439 if( (pAlt->eOperator & WO_IN) 2440 && (pAlt->pExpr->flags & EP_xIsSelect) 2441 && (pAlt->pExpr->x.pSelect->pEList->nExpr>1) 2442 ){ 2443 continue; 2444 } 2445 testcase( pAlt->eOperator & WO_EQ ); 2446 testcase( pAlt->eOperator & WO_IS ); 2447 testcase( pAlt->eOperator & WO_IN ); 2448 VdbeModuleComment((v, "begin transitive constraint")); 2449 sEAlt = *pAlt->pExpr; 2450 sEAlt.pLeft = pE->pLeft; 2451 sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL); 2452 pAlt->wtFlags |= TERM_CODED; 2453 } 2454 2455 /* For a LEFT OUTER JOIN, generate code that will record the fact that 2456 ** at least one row of the right table has matched the left table. 2457 */ 2458 if( pLevel->iLeftJoin ){ 2459 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); 2460 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); 2461 VdbeComment((v, "record LEFT JOIN hit")); 2462 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ 2463 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 2464 testcase( pTerm->wtFlags & TERM_CODED ); 2465 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 2466 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 2467 assert( pWInfo->untestedTerms ); 2468 continue; 2469 } 2470 assert( pTerm->pExpr ); 2471 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); 2472 pTerm->wtFlags |= TERM_CODED; 2473 } 2474 } 2475 2476 #if WHERETRACE_ENABLED /* 0x20800 */ 2477 if( sqlite3WhereTrace & 0x20000 ){ 2478 sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n", 2479 iLevel); 2480 sqlite3WhereClausePrint(pWC); 2481 } 2482 if( sqlite3WhereTrace & 0x800 ){ 2483 sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n", 2484 iLevel, (u64)pLevel->notReady); 2485 } 2486 #endif 2487 return pLevel->notReady; 2488 } 2489