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 ** This routine is a helper for explainIndexRange() below 26 ** 27 ** pStr holds the text of an expression that we are building up one term 28 ** at a time. This routine adds a new term to the end of the expression. 29 ** Terms are separated by AND so add the "AND" text for second and subsequent 30 ** terms only. 31 */ 32 static void explainAppendTerm( 33 StrAccum *pStr, /* The text expression being built */ 34 int iTerm, /* Index of this term. First is zero */ 35 const char *zColumn, /* Name of the column */ 36 const char *zOp /* Name of the operator */ 37 ){ 38 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5); 39 sqlite3StrAccumAppendAll(pStr, zColumn); 40 sqlite3StrAccumAppend(pStr, zOp, 1); 41 sqlite3StrAccumAppend(pStr, "?", 1); 42 } 43 44 /* 45 ** Argument pLevel describes a strategy for scanning table pTab. This 46 ** function appends text to pStr that describes the subset of table 47 ** rows scanned by the strategy in the form of an SQL expression. 48 ** 49 ** For example, if the query: 50 ** 51 ** SELECT * FROM t1 WHERE a=1 AND b>2; 52 ** 53 ** is run and there is an index on (a, b), then this function returns a 54 ** string similar to: 55 ** 56 ** "a=? AND b>?" 57 */ 58 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){ 59 Index *pIndex = pLoop->u.btree.pIndex; 60 u16 nEq = pLoop->u.btree.nEq; 61 u16 nSkip = pLoop->nSkip; 62 int i, j; 63 Column *aCol = pTab->aCol; 64 i16 *aiColumn = pIndex->aiColumn; 65 66 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; 67 sqlite3StrAccumAppend(pStr, " (", 2); 68 for(i=0; i<nEq; i++){ 69 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName; 70 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5); 71 sqlite3XPrintf(pStr, 0, i>=nSkip ? "%s=?" : "ANY(%s)", z); 72 } 73 74 j = i; 75 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ 76 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName; 77 explainAppendTerm(pStr, i++, z, ">"); 78 } 79 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ 80 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName; 81 explainAppendTerm(pStr, i, z, "<"); 82 } 83 sqlite3StrAccumAppend(pStr, ")", 1); 84 } 85 86 /* 87 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN 88 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was 89 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 90 ** is added to the output to describe the table scan strategy in pLevel. 91 ** 92 ** If an OP_Explain opcode is added to the VM, its address is returned. 93 ** Otherwise, if no OP_Explain is coded, zero is returned. 94 */ 95 int sqlite3WhereExplainOneScan( 96 Parse *pParse, /* Parse context */ 97 SrcList *pTabList, /* Table list this loop refers to */ 98 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ 99 int iLevel, /* Value for "level" column of output */ 100 int iFrom, /* Value for "from" column of output */ 101 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ 102 ){ 103 int ret = 0; 104 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS) 105 if( pParse->explain==2 ) 106 #endif 107 { 108 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; 109 Vdbe *v = pParse->pVdbe; /* VM being constructed */ 110 sqlite3 *db = pParse->db; /* Database handle */ 111 int iId = pParse->iSelectId; /* Select id (left-most output column) */ 112 int isSearch; /* True for a SEARCH. False for SCAN. */ 113 WhereLoop *pLoop; /* The controlling WhereLoop object */ 114 u32 flags; /* Flags that describe this loop */ 115 char *zMsg; /* Text to add to EQP output */ 116 StrAccum str; /* EQP output string */ 117 char zBuf[100]; /* Initial space for EQP output string */ 118 119 pLoop = pLevel->pWLoop; 120 flags = pLoop->wsFlags; 121 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0; 122 123 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 124 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) 125 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); 126 127 sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); 128 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); 129 if( pItem->pSelect ){ 130 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId); 131 }else{ 132 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName); 133 } 134 135 if( pItem->zAlias ){ 136 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias); 137 } 138 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ 139 const char *zFmt = 0; 140 Index *pIdx; 141 142 assert( pLoop->u.btree.pIndex!=0 ); 143 pIdx = pLoop->u.btree.pIndex; 144 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); 145 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ 146 if( isSearch ){ 147 zFmt = "PRIMARY KEY"; 148 } 149 }else if( flags & WHERE_PARTIALIDX ){ 150 zFmt = "AUTOMATIC PARTIAL COVERING INDEX"; 151 }else if( flags & WHERE_AUTO_INDEX ){ 152 zFmt = "AUTOMATIC COVERING INDEX"; 153 }else if( flags & WHERE_IDX_ONLY ){ 154 zFmt = "COVERING INDEX %s"; 155 }else{ 156 zFmt = "INDEX %s"; 157 } 158 if( zFmt ){ 159 sqlite3StrAccumAppend(&str, " USING ", 7); 160 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName); 161 explainIndexRange(&str, pLoop, pItem->pTab); 162 } 163 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ 164 const char *zRangeOp; 165 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ 166 zRangeOp = "="; 167 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ 168 zRangeOp = ">? AND rowid<"; 169 }else if( flags&WHERE_BTM_LIMIT ){ 170 zRangeOp = ">"; 171 }else{ 172 assert( flags&WHERE_TOP_LIMIT); 173 zRangeOp = "<"; 174 } 175 sqlite3XPrintf(&str, 0, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp); 176 } 177 #ifndef SQLITE_OMIT_VIRTUALTABLE 178 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ 179 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s", 180 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); 181 } 182 #endif 183 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS 184 if( pLoop->nOut>=10 ){ 185 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); 186 }else{ 187 sqlite3StrAccumAppend(&str, " (~1 row)", 9); 188 } 189 #endif 190 zMsg = sqlite3StrAccumFinish(&str); 191 ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC); 192 } 193 return ret; 194 } 195 #endif /* SQLITE_OMIT_EXPLAIN */ 196 197 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 198 /* 199 ** Configure the VM passed as the first argument with an 200 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 201 ** implement level pLvl. Argument pSrclist is a pointer to the FROM 202 ** clause that the scan reads data from. 203 ** 204 ** If argument addrExplain is not 0, it must be the address of an 205 ** OP_Explain instruction that describes the same loop. 206 */ 207 void sqlite3WhereAddScanStatus( 208 Vdbe *v, /* Vdbe to add scanstatus entry to */ 209 SrcList *pSrclist, /* FROM clause pLvl reads data from */ 210 WhereLevel *pLvl, /* Level to add scanstatus() entry for */ 211 int addrExplain /* Address of OP_Explain (or 0) */ 212 ){ 213 const char *zObj = 0; 214 WhereLoop *pLoop = pLvl->pWLoop; 215 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){ 216 zObj = pLoop->u.btree.pIndex->zName; 217 }else{ 218 zObj = pSrclist->a[pLvl->iFrom].zName; 219 } 220 sqlite3VdbeScanStatus( 221 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj 222 ); 223 } 224 #endif 225 226 227 /* 228 ** Disable a term in the WHERE clause. Except, do not disable the term 229 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON 230 ** or USING clause of that join. 231 ** 232 ** Consider the term t2.z='ok' in the following queries: 233 ** 234 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' 235 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' 236 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' 237 ** 238 ** The t2.z='ok' is disabled in the in (2) because it originates 239 ** in the ON clause. The term is disabled in (3) because it is not part 240 ** of a LEFT OUTER JOIN. In (1), the term is not disabled. 241 ** 242 ** Disabling a term causes that term to not be tested in the inner loop 243 ** of the join. Disabling is an optimization. When terms are satisfied 244 ** by indices, we disable them to prevent redundant tests in the inner 245 ** loop. We would get the correct results if nothing were ever disabled, 246 ** but joins might run a little slower. The trick is to disable as much 247 ** as we can without disabling too much. If we disabled in (1), we'd get 248 ** the wrong answer. See ticket #813. 249 ** 250 ** If all the children of a term are disabled, then that term is also 251 ** automatically disabled. In this way, terms get disabled if derived 252 ** virtual terms are tested first. For example: 253 ** 254 ** x GLOB 'abc*' AND x>='abc' AND x<'acd' 255 ** \___________/ \______/ \_____/ 256 ** parent child1 child2 257 ** 258 ** Only the parent term was in the original WHERE clause. The child1 259 ** and child2 terms were added by the LIKE optimization. If both of 260 ** the virtual child terms are valid, then testing of the parent can be 261 ** skipped. 262 ** 263 ** Usually the parent term is marked as TERM_CODED. But if the parent 264 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead. 265 ** The TERM_LIKECOND marking indicates that the term should be coded inside 266 ** a conditional such that is only evaluated on the second pass of a 267 ** LIKE-optimization loop, when scanning BLOBs instead of strings. 268 */ 269 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ 270 int nLoop = 0; 271 while( pTerm 272 && (pTerm->wtFlags & TERM_CODED)==0 273 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) 274 && (pLevel->notReady & pTerm->prereqAll)==0 275 ){ 276 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){ 277 pTerm->wtFlags |= TERM_LIKECOND; 278 }else{ 279 pTerm->wtFlags |= TERM_CODED; 280 } 281 if( pTerm->iParent<0 ) break; 282 pTerm = &pTerm->pWC->a[pTerm->iParent]; 283 pTerm->nChild--; 284 if( pTerm->nChild!=0 ) break; 285 nLoop++; 286 } 287 } 288 289 /* 290 ** Code an OP_Affinity opcode to apply the column affinity string zAff 291 ** to the n registers starting at base. 292 ** 293 ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the 294 ** beginning and end of zAff are ignored. If all entries in zAff are 295 ** SQLITE_AFF_BLOB, then no code gets generated. 296 ** 297 ** This routine makes its own copy of zAff so that the caller is free 298 ** to modify zAff after this routine returns. 299 */ 300 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ 301 Vdbe *v = pParse->pVdbe; 302 if( zAff==0 ){ 303 assert( pParse->db->mallocFailed ); 304 return; 305 } 306 assert( v!=0 ); 307 308 /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning 309 ** and end of the affinity string. 310 */ 311 while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){ 312 n--; 313 base++; 314 zAff++; 315 } 316 while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){ 317 n--; 318 } 319 320 /* Code the OP_Affinity opcode if there is anything left to do. */ 321 if( n>0 ){ 322 sqlite3VdbeAddOp2(v, OP_Affinity, base, n); 323 sqlite3VdbeChangeP4(v, -1, zAff, n); 324 sqlite3ExprCacheAffinityChange(pParse, base, n); 325 } 326 } 327 328 329 /* 330 ** Generate code for a single equality term of the WHERE clause. An equality 331 ** term can be either X=expr or X IN (...). pTerm is the term to be 332 ** coded. 333 ** 334 ** The current value for the constraint is left in register iReg. 335 ** 336 ** For a constraint of the form X=expr, the expression is evaluated and its 337 ** result is left on the stack. For constraints of the form X IN (...) 338 ** this routine sets up a loop that will iterate over all values of X. 339 */ 340 static int codeEqualityTerm( 341 Parse *pParse, /* The parsing context */ 342 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ 343 WhereLevel *pLevel, /* The level of the FROM clause we are working on */ 344 int iEq, /* Index of the equality term within this level */ 345 int bRev, /* True for reverse-order IN operations */ 346 int iTarget /* Attempt to leave results in this register */ 347 ){ 348 Expr *pX = pTerm->pExpr; 349 Vdbe *v = pParse->pVdbe; 350 int iReg; /* Register holding results */ 351 352 assert( iTarget>0 ); 353 if( pX->op==TK_EQ || pX->op==TK_IS ){ 354 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); 355 }else if( pX->op==TK_ISNULL ){ 356 iReg = iTarget; 357 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); 358 #ifndef SQLITE_OMIT_SUBQUERY 359 }else{ 360 int eType; 361 int iTab; 362 struct InLoop *pIn; 363 WhereLoop *pLoop = pLevel->pWLoop; 364 365 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 366 && pLoop->u.btree.pIndex!=0 367 && pLoop->u.btree.pIndex->aSortOrder[iEq] 368 ){ 369 testcase( iEq==0 ); 370 testcase( bRev ); 371 bRev = !bRev; 372 } 373 assert( pX->op==TK_IN ); 374 iReg = iTarget; 375 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0); 376 if( eType==IN_INDEX_INDEX_DESC ){ 377 testcase( bRev ); 378 bRev = !bRev; 379 } 380 iTab = pX->iTable; 381 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); 382 VdbeCoverageIf(v, bRev); 383 VdbeCoverageIf(v, !bRev); 384 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); 385 pLoop->wsFlags |= WHERE_IN_ABLE; 386 if( pLevel->u.in.nIn==0 ){ 387 pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 388 } 389 pLevel->u.in.nIn++; 390 pLevel->u.in.aInLoop = 391 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, 392 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); 393 pIn = pLevel->u.in.aInLoop; 394 if( pIn ){ 395 pIn += pLevel->u.in.nIn - 1; 396 pIn->iCur = iTab; 397 if( eType==IN_INDEX_ROWID ){ 398 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); 399 }else{ 400 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg); 401 } 402 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; 403 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v); 404 }else{ 405 pLevel->u.in.nIn = 0; 406 } 407 #endif 408 } 409 disableTerm(pLevel, pTerm); 410 return iReg; 411 } 412 413 /* 414 ** Generate code that will evaluate all == and IN constraints for an 415 ** index scan. 416 ** 417 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). 418 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 419 ** The index has as many as three equality constraints, but in this 420 ** example, the third "c" value is an inequality. So only two 421 ** constraints are coded. This routine will generate code to evaluate 422 ** a==5 and b IN (1,2,3). The current values for a and b will be stored 423 ** in consecutive registers and the index of the first register is returned. 424 ** 425 ** In the example above nEq==2. But this subroutine works for any value 426 ** of nEq including 0. If nEq==0, this routine is nearly a no-op. 427 ** The only thing it does is allocate the pLevel->iMem memory cell and 428 ** compute the affinity string. 429 ** 430 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints 431 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is 432 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that 433 ** occurs after the nEq quality constraints. 434 ** 435 ** This routine allocates a range of nEq+nExtraReg memory cells and returns 436 ** the index of the first memory cell in that range. The code that 437 ** calls this routine will use that memory range to store keys for 438 ** start and termination conditions of the loop. 439 ** key value of the loop. If one or more IN operators appear, then 440 ** this routine allocates an additional nEq memory cells for internal 441 ** use. 442 ** 443 ** Before returning, *pzAff is set to point to a buffer containing a 444 ** copy of the column affinity string of the index allocated using 445 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated 446 ** with equality constraints that use BLOB or NONE affinity are set to 447 ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following: 448 ** 449 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); 450 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; 451 ** 452 ** In the example above, the index on t1(a) has TEXT affinity. But since 453 ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity, 454 ** no conversion should be attempted before using a t2.b value as part of 455 ** a key to search the index. Hence the first byte in the returned affinity 456 ** string in this example would be set to SQLITE_AFF_BLOB. 457 */ 458 static int codeAllEqualityTerms( 459 Parse *pParse, /* Parsing context */ 460 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ 461 int bRev, /* Reverse the order of IN operators */ 462 int nExtraReg, /* Number of extra registers to allocate */ 463 char **pzAff /* OUT: Set to point to affinity string */ 464 ){ 465 u16 nEq; /* The number of == or IN constraints to code */ 466 u16 nSkip; /* Number of left-most columns to skip */ 467 Vdbe *v = pParse->pVdbe; /* The vm under construction */ 468 Index *pIdx; /* The index being used for this loop */ 469 WhereTerm *pTerm; /* A single constraint term */ 470 WhereLoop *pLoop; /* The WhereLoop object */ 471 int j; /* Loop counter */ 472 int regBase; /* Base register */ 473 int nReg; /* Number of registers to allocate */ 474 char *zAff; /* Affinity string to return */ 475 476 /* This module is only called on query plans that use an index. */ 477 pLoop = pLevel->pWLoop; 478 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); 479 nEq = pLoop->u.btree.nEq; 480 nSkip = pLoop->nSkip; 481 pIdx = pLoop->u.btree.pIndex; 482 assert( pIdx!=0 ); 483 484 /* Figure out how many memory cells we will need then allocate them. 485 */ 486 regBase = pParse->nMem + 1; 487 nReg = pLoop->u.btree.nEq + nExtraReg; 488 pParse->nMem += nReg; 489 490 zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx)); 491 if( !zAff ){ 492 pParse->db->mallocFailed = 1; 493 } 494 495 if( nSkip ){ 496 int iIdxCur = pLevel->iIdxCur; 497 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); 498 VdbeCoverageIf(v, bRev==0); 499 VdbeCoverageIf(v, bRev!=0); 500 VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); 501 j = sqlite3VdbeAddOp0(v, OP_Goto); 502 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), 503 iIdxCur, 0, regBase, nSkip); 504 VdbeCoverageIf(v, bRev==0); 505 VdbeCoverageIf(v, bRev!=0); 506 sqlite3VdbeJumpHere(v, j); 507 for(j=0; j<nSkip; j++){ 508 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); 509 assert( pIdx->aiColumn[j]>=0 ); 510 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName)); 511 } 512 } 513 514 /* Evaluate the equality constraints 515 */ 516 assert( zAff==0 || (int)strlen(zAff)>=nEq ); 517 for(j=nSkip; j<nEq; j++){ 518 int r1; 519 pTerm = pLoop->aLTerm[j]; 520 assert( pTerm!=0 ); 521 /* The following testcase is true for indices with redundant columns. 522 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ 523 testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); 524 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 525 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); 526 if( r1!=regBase+j ){ 527 if( nReg==1 ){ 528 sqlite3ReleaseTempReg(pParse, regBase); 529 regBase = r1; 530 }else{ 531 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); 532 } 533 } 534 testcase( pTerm->eOperator & WO_ISNULL ); 535 testcase( pTerm->eOperator & WO_IN ); 536 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ 537 Expr *pRight = pTerm->pExpr->pRight; 538 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){ 539 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); 540 VdbeCoverage(v); 541 } 542 if( zAff ){ 543 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){ 544 zAff[j] = SQLITE_AFF_BLOB; 545 } 546 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ 547 zAff[j] = SQLITE_AFF_BLOB; 548 } 549 } 550 } 551 } 552 *pzAff = zAff; 553 return regBase; 554 } 555 556 /* 557 ** If the most recently coded instruction is a constant range contraint 558 ** that originated from the LIKE optimization, then change the P3 to be 559 ** pLoop->iLikeRepCntr and set P5. 560 ** 561 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range 562 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range 563 ** scan loop run twice, once for strings and a second time for BLOBs. 564 ** The OP_String opcodes on the second pass convert the upper and lower 565 ** bound string contants to blobs. This routine makes the necessary changes 566 ** to the OP_String opcodes for that to happen. 567 */ 568 static void whereLikeOptimizationStringFixup( 569 Vdbe *v, /* prepared statement under construction */ 570 WhereLevel *pLevel, /* The loop that contains the LIKE operator */ 571 WhereTerm *pTerm /* The upper or lower bound just coded */ 572 ){ 573 if( pTerm->wtFlags & TERM_LIKEOPT ){ 574 VdbeOp *pOp; 575 assert( pLevel->iLikeRepCntr>0 ); 576 pOp = sqlite3VdbeGetOp(v, -1); 577 assert( pOp!=0 ); 578 assert( pOp->opcode==OP_String8 579 || pTerm->pWC->pWInfo->pParse->db->mallocFailed ); 580 pOp->p3 = pLevel->iLikeRepCntr; 581 pOp->p5 = 1; 582 } 583 } 584 585 586 /* 587 ** Generate code for the start of the iLevel-th loop in the WHERE clause 588 ** implementation described by pWInfo. 589 */ 590 Bitmask sqlite3WhereCodeOneLoopStart( 591 WhereInfo *pWInfo, /* Complete information about the WHERE clause */ 592 int iLevel, /* Which level of pWInfo->a[] should be coded */ 593 Bitmask notReady /* Which tables are currently available */ 594 ){ 595 int j, k; /* Loop counters */ 596 int iCur; /* The VDBE cursor for the table */ 597 int addrNxt; /* Where to jump to continue with the next IN case */ 598 int omitTable; /* True if we use the index only */ 599 int bRev; /* True if we need to scan in reverse order */ 600 WhereLevel *pLevel; /* The where level to be coded */ 601 WhereLoop *pLoop; /* The WhereLoop object being coded */ 602 WhereClause *pWC; /* Decomposition of the entire WHERE clause */ 603 WhereTerm *pTerm; /* A WHERE clause term */ 604 Parse *pParse; /* Parsing context */ 605 sqlite3 *db; /* Database connection */ 606 Vdbe *v; /* The prepared stmt under constructions */ 607 struct SrcList_item *pTabItem; /* FROM clause term being coded */ 608 int addrBrk; /* Jump here to break out of the loop */ 609 int addrCont; /* Jump here to continue with next cycle */ 610 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ 611 int iReleaseReg = 0; /* Temp register to free before returning */ 612 613 pParse = pWInfo->pParse; 614 v = pParse->pVdbe; 615 pWC = &pWInfo->sWC; 616 db = pParse->db; 617 pLevel = &pWInfo->a[iLevel]; 618 pLoop = pLevel->pWLoop; 619 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; 620 iCur = pTabItem->iCursor; 621 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); 622 bRev = (pWInfo->revMask>>iLevel)&1; 623 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 624 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0; 625 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); 626 627 /* Create labels for the "break" and "continue" instructions 628 ** for the current loop. Jump to addrBrk to break out of a loop. 629 ** Jump to cont to go immediately to the next iteration of the 630 ** loop. 631 ** 632 ** When there is an IN operator, we also have a "addrNxt" label that 633 ** means to continue with the next IN value combination. When 634 ** there are no IN operators in the constraints, the "addrNxt" label 635 ** is the same as "addrBrk". 636 */ 637 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); 638 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); 639 640 /* If this is the right table of a LEFT OUTER JOIN, allocate and 641 ** initialize a memory cell that records if this table matches any 642 ** row of the left table of the join. 643 */ 644 if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){ 645 pLevel->iLeftJoin = ++pParse->nMem; 646 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); 647 VdbeComment((v, "init LEFT JOIN no-match flag")); 648 } 649 650 /* Special case of a FROM clause subquery implemented as a co-routine */ 651 if( pTabItem->fg.viaCoroutine ){ 652 int regYield = pTabItem->regReturn; 653 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); 654 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); 655 VdbeCoverage(v); 656 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); 657 pLevel->op = OP_Goto; 658 }else 659 660 #ifndef SQLITE_OMIT_VIRTUALTABLE 661 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ 662 /* Case 1: The table is a virtual-table. Use the VFilter and VNext 663 ** to access the data. 664 */ 665 int iReg; /* P3 Value for OP_VFilter */ 666 int addrNotFound; 667 int nConstraint = pLoop->nLTerm; 668 669 sqlite3ExprCachePush(pParse); 670 iReg = sqlite3GetTempRange(pParse, nConstraint+2); 671 addrNotFound = pLevel->addrBrk; 672 for(j=0; j<nConstraint; j++){ 673 int iTarget = iReg+j+2; 674 pTerm = pLoop->aLTerm[j]; 675 if( pTerm==0 ) continue; 676 if( pTerm->eOperator & WO_IN ){ 677 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); 678 addrNotFound = pLevel->addrNxt; 679 }else{ 680 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget); 681 } 682 } 683 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); 684 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); 685 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, 686 pLoop->u.vtab.idxStr, 687 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); 688 VdbeCoverage(v); 689 pLoop->u.vtab.needFree = 0; 690 for(j=0; j<nConstraint && j<16; j++){ 691 if( (pLoop->u.vtab.omitMask>>j)&1 ){ 692 disableTerm(pLevel, pLoop->aLTerm[j]); 693 } 694 } 695 pLevel->op = OP_VNext; 696 pLevel->p1 = iCur; 697 pLevel->p2 = sqlite3VdbeCurrentAddr(v); 698 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); 699 sqlite3ExprCachePop(pParse); 700 }else 701 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 702 703 if( (pLoop->wsFlags & WHERE_IPK)!=0 704 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 705 ){ 706 /* Case 2: We can directly reference a single row using an 707 ** equality comparison against the ROWID field. Or 708 ** we reference multiple rows using a "rowid IN (...)" 709 ** construct. 710 */ 711 assert( pLoop->u.btree.nEq==1 ); 712 pTerm = pLoop->aLTerm[0]; 713 assert( pTerm!=0 ); 714 assert( pTerm->pExpr!=0 ); 715 assert( omitTable==0 ); 716 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 717 iReleaseReg = ++pParse->nMem; 718 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); 719 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); 720 addrNxt = pLevel->addrNxt; 721 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v); 722 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg); 723 VdbeCoverage(v); 724 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); 725 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 726 VdbeComment((v, "pk")); 727 pLevel->op = OP_Noop; 728 }else if( (pLoop->wsFlags & WHERE_IPK)!=0 729 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 730 ){ 731 /* Case 3: We have an inequality comparison against the ROWID field. 732 */ 733 int testOp = OP_Noop; 734 int start; 735 int memEndValue = 0; 736 WhereTerm *pStart, *pEnd; 737 738 assert( omitTable==0 ); 739 j = 0; 740 pStart = pEnd = 0; 741 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; 742 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; 743 assert( pStart!=0 || pEnd!=0 ); 744 if( bRev ){ 745 pTerm = pStart; 746 pStart = pEnd; 747 pEnd = pTerm; 748 } 749 if( pStart ){ 750 Expr *pX; /* The expression that defines the start bound */ 751 int r1, rTemp; /* Registers for holding the start boundary */ 752 753 /* The following constant maps TK_xx codes into corresponding 754 ** seek opcodes. It depends on a particular ordering of TK_xx 755 */ 756 const u8 aMoveOp[] = { 757 /* TK_GT */ OP_SeekGT, 758 /* TK_LE */ OP_SeekLE, 759 /* TK_LT */ OP_SeekLT, 760 /* TK_GE */ OP_SeekGE 761 }; 762 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ 763 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ 764 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ 765 766 assert( (pStart->wtFlags & TERM_VNULL)==0 ); 767 testcase( pStart->wtFlags & TERM_VIRTUAL ); 768 pX = pStart->pExpr; 769 assert( pX!=0 ); 770 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ 771 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); 772 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1); 773 VdbeComment((v, "pk")); 774 VdbeCoverageIf(v, pX->op==TK_GT); 775 VdbeCoverageIf(v, pX->op==TK_LE); 776 VdbeCoverageIf(v, pX->op==TK_LT); 777 VdbeCoverageIf(v, pX->op==TK_GE); 778 sqlite3ExprCacheAffinityChange(pParse, r1, 1); 779 sqlite3ReleaseTempReg(pParse, rTemp); 780 disableTerm(pLevel, pStart); 781 }else{ 782 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); 783 VdbeCoverageIf(v, bRev==0); 784 VdbeCoverageIf(v, bRev!=0); 785 } 786 if( pEnd ){ 787 Expr *pX; 788 pX = pEnd->pExpr; 789 assert( pX!=0 ); 790 assert( (pEnd->wtFlags & TERM_VNULL)==0 ); 791 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ 792 testcase( pEnd->wtFlags & TERM_VIRTUAL ); 793 memEndValue = ++pParse->nMem; 794 sqlite3ExprCode(pParse, pX->pRight, memEndValue); 795 if( pX->op==TK_LT || pX->op==TK_GT ){ 796 testOp = bRev ? OP_Le : OP_Ge; 797 }else{ 798 testOp = bRev ? OP_Lt : OP_Gt; 799 } 800 disableTerm(pLevel, pEnd); 801 } 802 start = sqlite3VdbeCurrentAddr(v); 803 pLevel->op = bRev ? OP_Prev : OP_Next; 804 pLevel->p1 = iCur; 805 pLevel->p2 = start; 806 assert( pLevel->p5==0 ); 807 if( testOp!=OP_Noop ){ 808 iRowidReg = ++pParse->nMem; 809 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); 810 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 811 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); 812 VdbeCoverageIf(v, testOp==OP_Le); 813 VdbeCoverageIf(v, testOp==OP_Lt); 814 VdbeCoverageIf(v, testOp==OP_Ge); 815 VdbeCoverageIf(v, testOp==OP_Gt); 816 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); 817 } 818 }else if( pLoop->wsFlags & WHERE_INDEXED ){ 819 /* Case 4: A scan using an index. 820 ** 821 ** The WHERE clause may contain zero or more equality 822 ** terms ("==" or "IN" operators) that refer to the N 823 ** left-most columns of the index. It may also contain 824 ** inequality constraints (>, <, >= or <=) on the indexed 825 ** column that immediately follows the N equalities. Only 826 ** the right-most column can be an inequality - the rest must 827 ** use the "==" and "IN" operators. For example, if the 828 ** index is on (x,y,z), then the following clauses are all 829 ** optimized: 830 ** 831 ** x=5 832 ** x=5 AND y=10 833 ** x=5 AND y<10 834 ** x=5 AND y>5 AND y<10 835 ** x=5 AND y=5 AND z<=10 836 ** 837 ** The z<10 term of the following cannot be used, only 838 ** the x=5 term: 839 ** 840 ** x=5 AND z<10 841 ** 842 ** N may be zero if there are inequality constraints. 843 ** If there are no inequality constraints, then N is at 844 ** least one. 845 ** 846 ** This case is also used when there are no WHERE clause 847 ** constraints but an index is selected anyway, in order 848 ** to force the output order to conform to an ORDER BY. 849 */ 850 static const u8 aStartOp[] = { 851 0, 852 0, 853 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ 854 OP_Last, /* 3: (!start_constraints && startEq && bRev) */ 855 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ 856 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ 857 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ 858 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ 859 }; 860 static const u8 aEndOp[] = { 861 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ 862 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ 863 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ 864 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ 865 }; 866 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ 867 int regBase; /* Base register holding constraint values */ 868 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ 869 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ 870 int startEq; /* True if range start uses ==, >= or <= */ 871 int endEq; /* True if range end uses ==, >= or <= */ 872 int start_constraints; /* Start of range is constrained */ 873 int nConstraint; /* Number of constraint terms */ 874 Index *pIdx; /* The index we will be using */ 875 int iIdxCur; /* The VDBE cursor for the index */ 876 int nExtraReg = 0; /* Number of extra registers needed */ 877 int op; /* Instruction opcode */ 878 char *zStartAff; /* Affinity for start of range constraint */ 879 char cEndAff = 0; /* Affinity for end of range constraint */ 880 u8 bSeekPastNull = 0; /* True to seek past initial nulls */ 881 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ 882 883 pIdx = pLoop->u.btree.pIndex; 884 iIdxCur = pLevel->iIdxCur; 885 assert( nEq>=pLoop->nSkip ); 886 887 /* If this loop satisfies a sort order (pOrderBy) request that 888 ** was passed to this function to implement a "SELECT min(x) ..." 889 ** query, then the caller will only allow the loop to run for 890 ** a single iteration. This means that the first row returned 891 ** should not have a NULL value stored in 'x'. If column 'x' is 892 ** the first one after the nEq equality constraints in the index, 893 ** this requires some special handling. 894 */ 895 assert( pWInfo->pOrderBy==0 896 || pWInfo->pOrderBy->nExpr==1 897 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); 898 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 899 && pWInfo->nOBSat>0 900 && (pIdx->nKeyCol>nEq) 901 ){ 902 assert( pLoop->nSkip==0 ); 903 bSeekPastNull = 1; 904 nExtraReg = 1; 905 } 906 907 /* Find any inequality constraint terms for the start and end 908 ** of the range. 909 */ 910 j = nEq; 911 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ 912 pRangeStart = pLoop->aLTerm[j++]; 913 nExtraReg = 1; 914 /* Like optimization range constraints always occur in pairs */ 915 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 916 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 ); 917 } 918 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ 919 pRangeEnd = pLoop->aLTerm[j++]; 920 nExtraReg = 1; 921 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){ 922 assert( pRangeStart!=0 ); /* LIKE opt constraints */ 923 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */ 924 pLevel->iLikeRepCntr = ++pParse->nMem; 925 testcase( bRev ); 926 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC ); 927 sqlite3VdbeAddOp2(v, OP_Integer, 928 bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC), 929 pLevel->iLikeRepCntr); 930 VdbeComment((v, "LIKE loop counter")); 931 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v); 932 } 933 if( pRangeStart==0 934 && (j = pIdx->aiColumn[nEq])>=0 935 && pIdx->pTable->aCol[j].notNull==0 936 ){ 937 bSeekPastNull = 1; 938 } 939 } 940 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); 941 942 /* Generate code to evaluate all constraint terms using == or IN 943 ** and store the values of those terms in an array of registers 944 ** starting at regBase. 945 */ 946 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); 947 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); 948 if( zStartAff ) cEndAff = zStartAff[nEq]; 949 addrNxt = pLevel->addrNxt; 950 951 /* If we are doing a reverse order scan on an ascending index, or 952 ** a forward order scan on a descending index, interchange the 953 ** start and end terms (pRangeStart and pRangeEnd). 954 */ 955 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) 956 || (bRev && pIdx->nKeyCol==nEq) 957 ){ 958 SWAP(WhereTerm *, pRangeEnd, pRangeStart); 959 SWAP(u8, bSeekPastNull, bStopAtNull); 960 } 961 962 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); 963 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); 964 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); 965 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); 966 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); 967 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); 968 start_constraints = pRangeStart || nEq>0; 969 970 /* Seek the index cursor to the start of the range. */ 971 nConstraint = nEq; 972 if( pRangeStart ){ 973 Expr *pRight = pRangeStart->pExpr->pRight; 974 sqlite3ExprCode(pParse, pRight, regBase+nEq); 975 whereLikeOptimizationStringFixup(v, pLevel, pRangeStart); 976 if( (pRangeStart->wtFlags & TERM_VNULL)==0 977 && sqlite3ExprCanBeNull(pRight) 978 ){ 979 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 980 VdbeCoverage(v); 981 } 982 if( zStartAff ){ 983 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){ 984 /* Since the comparison is to be performed with no conversions 985 ** applied to the operands, set the affinity to apply to pRight to 986 ** SQLITE_AFF_BLOB. */ 987 zStartAff[nEq] = SQLITE_AFF_BLOB; 988 } 989 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){ 990 zStartAff[nEq] = SQLITE_AFF_BLOB; 991 } 992 } 993 nConstraint++; 994 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); 995 }else if( bSeekPastNull ){ 996 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 997 nConstraint++; 998 startEq = 0; 999 start_constraints = 1; 1000 } 1001 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); 1002 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; 1003 assert( op!=0 ); 1004 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 1005 VdbeCoverage(v); 1006 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); 1007 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); 1008 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); 1009 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); 1010 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); 1011 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); 1012 1013 /* Load the value for the inequality constraint at the end of the 1014 ** range (if any). 1015 */ 1016 nConstraint = nEq; 1017 if( pRangeEnd ){ 1018 Expr *pRight = pRangeEnd->pExpr->pRight; 1019 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); 1020 sqlite3ExprCode(pParse, pRight, regBase+nEq); 1021 whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd); 1022 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 1023 && sqlite3ExprCanBeNull(pRight) 1024 ){ 1025 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); 1026 VdbeCoverage(v); 1027 } 1028 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB 1029 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff) 1030 ){ 1031 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff); 1032 } 1033 nConstraint++; 1034 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); 1035 }else if( bStopAtNull ){ 1036 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); 1037 endEq = 0; 1038 nConstraint++; 1039 } 1040 sqlite3DbFree(db, zStartAff); 1041 1042 /* Top of the loop body */ 1043 pLevel->p2 = sqlite3VdbeCurrentAddr(v); 1044 1045 /* Check if the index cursor is past the end of the range. */ 1046 if( nConstraint ){ 1047 op = aEndOp[bRev*2 + endEq]; 1048 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); 1049 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); 1050 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); 1051 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); 1052 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); 1053 } 1054 1055 /* Seek the table cursor, if required */ 1056 disableTerm(pLevel, pRangeStart); 1057 disableTerm(pLevel, pRangeEnd); 1058 if( omitTable ){ 1059 /* pIdx is a covering index. No need to access the main table. */ 1060 }else if( HasRowid(pIdx->pTable) ){ 1061 iRowidReg = ++pParse->nMem; 1062 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); 1063 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); 1064 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */ 1065 }else if( iCur!=iIdxCur ){ 1066 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); 1067 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); 1068 for(j=0; j<pPk->nKeyCol; j++){ 1069 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); 1070 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); 1071 } 1072 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, 1073 iRowidReg, pPk->nKeyCol); VdbeCoverage(v); 1074 } 1075 1076 /* Record the instruction used to terminate the loop. Disable 1077 ** WHERE clause terms made redundant by the index range scan. 1078 */ 1079 if( pLoop->wsFlags & WHERE_ONEROW ){ 1080 pLevel->op = OP_Noop; 1081 }else if( bRev ){ 1082 pLevel->op = OP_Prev; 1083 }else{ 1084 pLevel->op = OP_Next; 1085 } 1086 pLevel->p1 = iIdxCur; 1087 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; 1088 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ 1089 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 1090 }else{ 1091 assert( pLevel->p5==0 ); 1092 } 1093 }else 1094 1095 #ifndef SQLITE_OMIT_OR_OPTIMIZATION 1096 if( pLoop->wsFlags & WHERE_MULTI_OR ){ 1097 /* Case 5: Two or more separately indexed terms connected by OR 1098 ** 1099 ** Example: 1100 ** 1101 ** CREATE TABLE t1(a,b,c,d); 1102 ** CREATE INDEX i1 ON t1(a); 1103 ** CREATE INDEX i2 ON t1(b); 1104 ** CREATE INDEX i3 ON t1(c); 1105 ** 1106 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) 1107 ** 1108 ** In the example, there are three indexed terms connected by OR. 1109 ** The top of the loop looks like this: 1110 ** 1111 ** Null 1 # Zero the rowset in reg 1 1112 ** 1113 ** Then, for each indexed term, the following. The arguments to 1114 ** RowSetTest are such that the rowid of the current row is inserted 1115 ** into the RowSet. If it is already present, control skips the 1116 ** Gosub opcode and jumps straight to the code generated by WhereEnd(). 1117 ** 1118 ** sqlite3WhereBegin(<term>) 1119 ** RowSetTest # Insert rowid into rowset 1120 ** Gosub 2 A 1121 ** sqlite3WhereEnd() 1122 ** 1123 ** Following the above, code to terminate the loop. Label A, the target 1124 ** of the Gosub above, jumps to the instruction right after the Goto. 1125 ** 1126 ** Null 1 # Zero the rowset in reg 1 1127 ** Goto B # The loop is finished. 1128 ** 1129 ** A: <loop body> # Return data, whatever. 1130 ** 1131 ** Return 2 # Jump back to the Gosub 1132 ** 1133 ** B: <after the loop> 1134 ** 1135 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then 1136 ** use an ephemeral index instead of a RowSet to record the primary 1137 ** keys of the rows we have already seen. 1138 ** 1139 */ 1140 WhereClause *pOrWc; /* The OR-clause broken out into subterms */ 1141 SrcList *pOrTab; /* Shortened table list or OR-clause generation */ 1142 Index *pCov = 0; /* Potential covering index (or NULL) */ 1143 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ 1144 1145 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ 1146 int regRowset = 0; /* Register for RowSet object */ 1147 int regRowid = 0; /* Register holding rowid */ 1148 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ 1149 int iRetInit; /* Address of regReturn init */ 1150 int untestedTerms = 0; /* Some terms not completely tested */ 1151 int ii; /* Loop counter */ 1152 u16 wctrlFlags; /* Flags for sub-WHERE clause */ 1153 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ 1154 Table *pTab = pTabItem->pTab; 1155 1156 pTerm = pLoop->aLTerm[0]; 1157 assert( pTerm!=0 ); 1158 assert( pTerm->eOperator & WO_OR ); 1159 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); 1160 pOrWc = &pTerm->u.pOrInfo->wc; 1161 pLevel->op = OP_Return; 1162 pLevel->p1 = regReturn; 1163 1164 /* Set up a new SrcList in pOrTab containing the table being scanned 1165 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. 1166 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). 1167 */ 1168 if( pWInfo->nLevel>1 ){ 1169 int nNotReady; /* The number of notReady tables */ 1170 struct SrcList_item *origSrc; /* Original list of tables */ 1171 nNotReady = pWInfo->nLevel - iLevel - 1; 1172 pOrTab = sqlite3StackAllocRaw(db, 1173 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); 1174 if( pOrTab==0 ) return notReady; 1175 pOrTab->nAlloc = (u8)(nNotReady + 1); 1176 pOrTab->nSrc = pOrTab->nAlloc; 1177 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); 1178 origSrc = pWInfo->pTabList->a; 1179 for(k=1; k<=nNotReady; k++){ 1180 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); 1181 } 1182 }else{ 1183 pOrTab = pWInfo->pTabList; 1184 } 1185 1186 /* Initialize the rowset register to contain NULL. An SQL NULL is 1187 ** equivalent to an empty rowset. Or, create an ephemeral index 1188 ** capable of holding primary keys in the case of a WITHOUT ROWID. 1189 ** 1190 ** Also initialize regReturn to contain the address of the instruction 1191 ** immediately following the OP_Return at the bottom of the loop. This 1192 ** is required in a few obscure LEFT JOIN cases where control jumps 1193 ** over the top of the loop into the body of it. In this case the 1194 ** correct response for the end-of-loop code (the OP_Return) is to 1195 ** fall through to the next instruction, just as an OP_Next does if 1196 ** called on an uninitialized cursor. 1197 */ 1198 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 1199 if( HasRowid(pTab) ){ 1200 regRowset = ++pParse->nMem; 1201 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); 1202 }else{ 1203 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 1204 regRowset = pParse->nTab++; 1205 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); 1206 sqlite3VdbeSetP4KeyInfo(pParse, pPk); 1207 } 1208 regRowid = ++pParse->nMem; 1209 } 1210 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); 1211 1212 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y 1213 ** Then for every term xN, evaluate as the subexpression: xN AND z 1214 ** That way, terms in y that are factored into the disjunction will 1215 ** be picked up by the recursive calls to sqlite3WhereBegin() below. 1216 ** 1217 ** Actually, each subexpression is converted to "xN AND w" where w is 1218 ** the "interesting" terms of z - terms that did not originate in the 1219 ** ON or USING clause of a LEFT JOIN, and terms that are usable as 1220 ** indices. 1221 ** 1222 ** This optimization also only applies if the (x1 OR x2 OR ...) term 1223 ** is not contained in the ON clause of a LEFT JOIN. 1224 ** See ticket http://www.sqlite.org/src/info/f2369304e4 1225 */ 1226 if( pWC->nTerm>1 ){ 1227 int iTerm; 1228 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ 1229 Expr *pExpr = pWC->a[iTerm].pExpr; 1230 if( &pWC->a[iTerm] == pTerm ) continue; 1231 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; 1232 if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue; 1233 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; 1234 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); 1235 pExpr = sqlite3ExprDup(db, pExpr, 0); 1236 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); 1237 } 1238 if( pAndExpr ){ 1239 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0); 1240 } 1241 } 1242 1243 /* Run a separate WHERE clause for each term of the OR clause. After 1244 ** eliminating duplicates from other WHERE clauses, the action for each 1245 ** sub-WHERE clause is to to invoke the main loop body as a subroutine. 1246 */ 1247 wctrlFlags = WHERE_OMIT_OPEN_CLOSE 1248 | WHERE_FORCE_TABLE 1249 | WHERE_ONETABLE_ONLY 1250 | WHERE_NO_AUTOINDEX; 1251 for(ii=0; ii<pOrWc->nTerm; ii++){ 1252 WhereTerm *pOrTerm = &pOrWc->a[ii]; 1253 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ 1254 WhereInfo *pSubWInfo; /* Info for single OR-term scan */ 1255 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ 1256 int j1 = 0; /* Address of jump operation */ 1257 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ 1258 pAndExpr->pLeft = pOrExpr; 1259 pOrExpr = pAndExpr; 1260 } 1261 /* Loop through table entries that match term pOrTerm. */ 1262 WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); 1263 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, 1264 wctrlFlags, iCovCur); 1265 assert( pSubWInfo || pParse->nErr || db->mallocFailed ); 1266 if( pSubWInfo ){ 1267 WhereLoop *pSubLoop; 1268 int addrExplain = sqlite3WhereExplainOneScan( 1269 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 1270 ); 1271 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain); 1272 1273 /* This is the sub-WHERE clause body. First skip over 1274 ** duplicate rows from prior sub-WHERE clauses, and record the 1275 ** rowid (or PRIMARY KEY) for the current row so that the same 1276 ** row will be skipped in subsequent sub-WHERE clauses. 1277 */ 1278 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ 1279 int r; 1280 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); 1281 if( HasRowid(pTab) ){ 1282 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); 1283 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet); 1284 VdbeCoverage(v); 1285 }else{ 1286 Index *pPk = sqlite3PrimaryKeyIndex(pTab); 1287 int nPk = pPk->nKeyCol; 1288 int iPk; 1289 1290 /* Read the PK into an array of temp registers. */ 1291 r = sqlite3GetTempRange(pParse, nPk); 1292 for(iPk=0; iPk<nPk; iPk++){ 1293 int iCol = pPk->aiColumn[iPk]; 1294 int rx; 1295 rx = sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur,r+iPk,0); 1296 if( rx!=r+iPk ){ 1297 sqlite3VdbeAddOp2(v, OP_SCopy, rx, r+iPk); 1298 } 1299 } 1300 1301 /* Check if the temp table already contains this key. If so, 1302 ** the row has already been included in the result set and 1303 ** can be ignored (by jumping past the Gosub below). Otherwise, 1304 ** insert the key into the temp table and proceed with processing 1305 ** the row. 1306 ** 1307 ** Use some of the same optimizations as OP_RowSetTest: If iSet 1308 ** is zero, assume that the key cannot already be present in 1309 ** the temp table. And if iSet is -1, assume that there is no 1310 ** need to insert the key into the temp table, as it will never 1311 ** be tested for. */ 1312 if( iSet ){ 1313 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); 1314 VdbeCoverage(v); 1315 } 1316 if( iSet>=0 ){ 1317 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); 1318 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0); 1319 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); 1320 } 1321 1322 /* Release the array of temp registers */ 1323 sqlite3ReleaseTempRange(pParse, r, nPk); 1324 } 1325 } 1326 1327 /* Invoke the main loop body as a subroutine */ 1328 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); 1329 1330 /* Jump here (skipping the main loop body subroutine) if the 1331 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ 1332 if( j1 ) sqlite3VdbeJumpHere(v, j1); 1333 1334 /* The pSubWInfo->untestedTerms flag means that this OR term 1335 ** contained one or more AND term from a notReady table. The 1336 ** terms from the notReady table could not be tested and will 1337 ** need to be tested later. 1338 */ 1339 if( pSubWInfo->untestedTerms ) untestedTerms = 1; 1340 1341 /* If all of the OR-connected terms are optimized using the same 1342 ** index, and the index is opened using the same cursor number 1343 ** by each call to sqlite3WhereBegin() made by this loop, it may 1344 ** be possible to use that index as a covering index. 1345 ** 1346 ** If the call to sqlite3WhereBegin() above resulted in a scan that 1347 ** uses an index, and this is either the first OR-connected term 1348 ** processed or the index is the same as that used by all previous 1349 ** terms, set pCov to the candidate covering index. Otherwise, set 1350 ** pCov to NULL to indicate that no candidate covering index will 1351 ** be available. 1352 */ 1353 pSubLoop = pSubWInfo->a[0].pWLoop; 1354 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); 1355 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 1356 && (ii==0 || pSubLoop->u.btree.pIndex==pCov) 1357 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) 1358 ){ 1359 assert( pSubWInfo->a[0].iIdxCur==iCovCur ); 1360 pCov = pSubLoop->u.btree.pIndex; 1361 wctrlFlags |= WHERE_REOPEN_IDX; 1362 }else{ 1363 pCov = 0; 1364 } 1365 1366 /* Finish the loop through table entries that match term pOrTerm. */ 1367 sqlite3WhereEnd(pSubWInfo); 1368 } 1369 } 1370 } 1371 pLevel->u.pCovidx = pCov; 1372 if( pCov ) pLevel->iIdxCur = iCovCur; 1373 if( pAndExpr ){ 1374 pAndExpr->pLeft = 0; 1375 sqlite3ExprDelete(db, pAndExpr); 1376 } 1377 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); 1378 sqlite3VdbeGoto(v, pLevel->addrBrk); 1379 sqlite3VdbeResolveLabel(v, iLoopBody); 1380 1381 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); 1382 if( !untestedTerms ) disableTerm(pLevel, pTerm); 1383 }else 1384 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 1385 1386 { 1387 /* Case 6: There is no usable index. We must do a complete 1388 ** scan of the entire table. 1389 */ 1390 static const u8 aStep[] = { OP_Next, OP_Prev }; 1391 static const u8 aStart[] = { OP_Rewind, OP_Last }; 1392 assert( bRev==0 || bRev==1 ); 1393 if( pTabItem->fg.isRecursive ){ 1394 /* Tables marked isRecursive have only a single row that is stored in 1395 ** a pseudo-cursor. No need to Rewind or Next such cursors. */ 1396 pLevel->op = OP_Noop; 1397 }else{ 1398 pLevel->op = aStep[bRev]; 1399 pLevel->p1 = iCur; 1400 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); 1401 VdbeCoverageIf(v, bRev==0); 1402 VdbeCoverageIf(v, bRev!=0); 1403 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; 1404 } 1405 } 1406 1407 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS 1408 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v); 1409 #endif 1410 1411 /* Insert code to test every subexpression that can be completely 1412 ** computed using the current set of tables. 1413 */ 1414 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 1415 Expr *pE; 1416 int skipLikeAddr = 0; 1417 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 1418 testcase( pTerm->wtFlags & TERM_CODED ); 1419 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 1420 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 1421 testcase( pWInfo->untestedTerms==0 1422 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ); 1423 pWInfo->untestedTerms = 1; 1424 continue; 1425 } 1426 pE = pTerm->pExpr; 1427 assert( pE!=0 ); 1428 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ 1429 continue; 1430 } 1431 if( pTerm->wtFlags & TERM_LIKECOND ){ 1432 assert( pLevel->iLikeRepCntr>0 ); 1433 skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr); 1434 VdbeCoverage(v); 1435 } 1436 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); 1437 if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr); 1438 pTerm->wtFlags |= TERM_CODED; 1439 } 1440 1441 /* Insert code to test for implied constraints based on transitivity 1442 ** of the "==" operator. 1443 ** 1444 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" 1445 ** and we are coding the t1 loop and the t2 loop has not yet coded, 1446 ** then we cannot use the "t1.a=t2.b" constraint, but we can code 1447 ** the implied "t1.a=123" constraint. 1448 */ 1449 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ 1450 Expr *pE, *pEAlt; 1451 WhereTerm *pAlt; 1452 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 1453 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue; 1454 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue; 1455 if( pTerm->leftCursor!=iCur ) continue; 1456 if( pLevel->iLeftJoin ) continue; 1457 pE = pTerm->pExpr; 1458 assert( !ExprHasProperty(pE, EP_FromJoin) ); 1459 assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); 1460 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady, 1461 WO_EQ|WO_IN|WO_IS, 0); 1462 if( pAlt==0 ) continue; 1463 if( pAlt->wtFlags & (TERM_CODED) ) continue; 1464 testcase( pAlt->eOperator & WO_EQ ); 1465 testcase( pAlt->eOperator & WO_IS ); 1466 testcase( pAlt->eOperator & WO_IN ); 1467 VdbeModuleComment((v, "begin transitive constraint")); 1468 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt)); 1469 if( pEAlt ){ 1470 *pEAlt = *pAlt->pExpr; 1471 pEAlt->pLeft = pE->pLeft; 1472 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL); 1473 sqlite3StackFree(db, pEAlt); 1474 } 1475 } 1476 1477 /* For a LEFT OUTER JOIN, generate code that will record the fact that 1478 ** at least one row of the right table has matched the left table. 1479 */ 1480 if( pLevel->iLeftJoin ){ 1481 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); 1482 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); 1483 VdbeComment((v, "record LEFT JOIN hit")); 1484 sqlite3ExprCacheClear(pParse); 1485 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ 1486 testcase( pTerm->wtFlags & TERM_VIRTUAL ); 1487 testcase( pTerm->wtFlags & TERM_CODED ); 1488 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; 1489 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ 1490 assert( pWInfo->untestedTerms ); 1491 continue; 1492 } 1493 assert( pTerm->pExpr ); 1494 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); 1495 pTerm->wtFlags |= TERM_CODED; 1496 } 1497 } 1498 1499 return pLevel->notReady; 1500 } 1501