1 /* 2 ** 2015-06-08 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 originally part of where.c but was split out to improve 16 ** readability and editabiliity. This file contains utility routines for 17 ** analyzing Expr objects in the WHERE clause. 18 */ 19 #include "sqliteInt.h" 20 #include "whereInt.h" 21 22 /* Forward declarations */ 23 static void exprAnalyze(SrcList*, WhereClause*, int); 24 25 /* 26 ** Deallocate all memory associated with a WhereOrInfo object. 27 */ 28 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ 29 sqlite3WhereClauseClear(&p->wc); 30 sqlite3DbFree(db, p); 31 } 32 33 /* 34 ** Deallocate all memory associated with a WhereAndInfo object. 35 */ 36 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ 37 sqlite3WhereClauseClear(&p->wc); 38 sqlite3DbFree(db, p); 39 } 40 41 /* 42 ** Add a single new WhereTerm entry to the WhereClause object pWC. 43 ** The new WhereTerm object is constructed from Expr p and with wtFlags. 44 ** The index in pWC->a[] of the new WhereTerm is returned on success. 45 ** 0 is returned if the new WhereTerm could not be added due to a memory 46 ** allocation error. The memory allocation failure will be recorded in 47 ** the db->mallocFailed flag so that higher-level functions can detect it. 48 ** 49 ** This routine will increase the size of the pWC->a[] array as necessary. 50 ** 51 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility 52 ** for freeing the expression p is assumed by the WhereClause object pWC. 53 ** This is true even if this routine fails to allocate a new WhereTerm. 54 ** 55 ** WARNING: This routine might reallocate the space used to store 56 ** WhereTerms. All pointers to WhereTerms should be invalidated after 57 ** calling this routine. Such pointers may be reinitialized by referencing 58 ** the pWC->a[] array. 59 */ 60 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){ 61 WhereTerm *pTerm; 62 int idx; 63 testcase( wtFlags & TERM_VIRTUAL ); 64 if( pWC->nTerm>=pWC->nSlot ){ 65 WhereTerm *pOld = pWC->a; 66 sqlite3 *db = pWC->pWInfo->pParse->db; 67 pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); 68 if( pWC->a==0 ){ 69 if( wtFlags & TERM_DYNAMIC ){ 70 sqlite3ExprDelete(db, p); 71 } 72 pWC->a = pOld; 73 return 0; 74 } 75 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); 76 if( pOld!=pWC->aStatic ){ 77 sqlite3DbFree(db, pOld); 78 } 79 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); 80 } 81 pTerm = &pWC->a[idx = pWC->nTerm++]; 82 if( p && ExprHasProperty(p, EP_Unlikely) ){ 83 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270; 84 }else{ 85 pTerm->truthProb = 1; 86 } 87 pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p); 88 pTerm->wtFlags = wtFlags; 89 pTerm->pWC = pWC; 90 pTerm->iParent = -1; 91 memset(&pTerm->eOperator, 0, 92 sizeof(WhereTerm) - offsetof(WhereTerm,eOperator)); 93 return idx; 94 } 95 96 /* 97 ** Return TRUE if the given operator is one of the operators that is 98 ** allowed for an indexable WHERE clause term. The allowed operators are 99 ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL" 100 */ 101 static int allowedOp(int op){ 102 assert( TK_GT>TK_EQ && TK_GT<TK_GE ); 103 assert( TK_LT>TK_EQ && TK_LT<TK_GE ); 104 assert( TK_LE>TK_EQ && TK_LE<TK_GE ); 105 assert( TK_GE==TK_EQ+4 ); 106 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS; 107 } 108 109 /* 110 ** Commute a comparison operator. Expressions of the form "X op Y" 111 ** are converted into "Y op X". 112 */ 113 static u16 exprCommute(Parse *pParse, Expr *pExpr){ 114 if( pExpr->pLeft->op==TK_VECTOR 115 || pExpr->pRight->op==TK_VECTOR 116 || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) != 117 sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft) 118 ){ 119 pExpr->flags ^= EP_Commuted; 120 } 121 SWAP(Expr*,pExpr->pRight,pExpr->pLeft); 122 if( pExpr->op>=TK_GT ){ 123 assert( TK_LT==TK_GT+2 ); 124 assert( TK_GE==TK_LE+2 ); 125 assert( TK_GT>TK_EQ ); 126 assert( TK_GT<TK_LE ); 127 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE ); 128 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; 129 } 130 return 0; 131 } 132 133 /* 134 ** Translate from TK_xx operator to WO_xx bitmask. 135 */ 136 static u16 operatorMask(int op){ 137 u16 c; 138 assert( allowedOp(op) ); 139 if( op==TK_IN ){ 140 c = WO_IN; 141 }else if( op==TK_ISNULL ){ 142 c = WO_ISNULL; 143 }else if( op==TK_IS ){ 144 c = WO_IS; 145 }else{ 146 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff ); 147 c = (u16)(WO_EQ<<(op-TK_EQ)); 148 } 149 assert( op!=TK_ISNULL || c==WO_ISNULL ); 150 assert( op!=TK_IN || c==WO_IN ); 151 assert( op!=TK_EQ || c==WO_EQ ); 152 assert( op!=TK_LT || c==WO_LT ); 153 assert( op!=TK_LE || c==WO_LE ); 154 assert( op!=TK_GT || c==WO_GT ); 155 assert( op!=TK_GE || c==WO_GE ); 156 assert( op!=TK_IS || c==WO_IS ); 157 return c; 158 } 159 160 161 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION 162 /* 163 ** Check to see if the given expression is a LIKE or GLOB operator that 164 ** can be optimized using inequality constraints. Return TRUE if it is 165 ** so and false if not. 166 ** 167 ** In order for the operator to be optimizible, the RHS must be a string 168 ** literal that does not begin with a wildcard. The LHS must be a column 169 ** that may only be NULL, a string, or a BLOB, never a number. (This means 170 ** that virtual tables cannot participate in the LIKE optimization.) The 171 ** collating sequence for the column on the LHS must be appropriate for 172 ** the operator. 173 */ 174 static int isLikeOrGlob( 175 Parse *pParse, /* Parsing and code generating context */ 176 Expr *pExpr, /* Test this expression */ 177 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */ 178 int *pisComplete, /* True if the only wildcard is % in the last character */ 179 int *pnoCase /* True if uppercase is equivalent to lowercase */ 180 ){ 181 const u8 *z = 0; /* String on RHS of LIKE operator */ 182 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ 183 ExprList *pList; /* List of operands to the LIKE operator */ 184 u8 c; /* One character in z[] */ 185 int cnt; /* Number of non-wildcard prefix characters */ 186 u8 wc[4]; /* Wildcard characters */ 187 sqlite3 *db = pParse->db; /* Database connection */ 188 sqlite3_value *pVal = 0; 189 int op; /* Opcode of pRight */ 190 int rc; /* Result code to return */ 191 192 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){ 193 return 0; 194 } 195 #ifdef SQLITE_EBCDIC 196 if( *pnoCase ) return 0; 197 #endif 198 pList = pExpr->x.pList; 199 pLeft = pList->a[1].pExpr; 200 201 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr); 202 op = pRight->op; 203 if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){ 204 Vdbe *pReprepare = pParse->pReprepare; 205 int iCol = pRight->iColumn; 206 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB); 207 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ 208 z = sqlite3_value_text(pVal); 209 } 210 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); 211 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); 212 }else if( op==TK_STRING ){ 213 z = (u8*)pRight->u.zToken; 214 } 215 if( z ){ 216 217 /* Count the number of prefix characters prior to the first wildcard */ 218 cnt = 0; 219 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ 220 cnt++; 221 if( c==wc[3] && z[cnt]!=0 ) cnt++; 222 } 223 224 /* The optimization is possible only if (1) the pattern does not begin 225 ** with a wildcard and if (2) the non-wildcard prefix does not end with 226 ** an (illegal 0xff) character, or (3) the pattern does not consist of 227 ** a single escape character. The second condition is necessary so 228 ** that we can increment the prefix key to find an upper bound for the 229 ** range search. The third is because the caller assumes that the pattern 230 ** consists of at least one character after all escapes have been 231 ** removed. */ 232 if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){ 233 Expr *pPrefix; 234 235 /* A "complete" match if the pattern ends with "*" or "%" */ 236 *pisComplete = c==wc[0] && z[cnt+1]==0; 237 238 /* Get the pattern prefix. Remove all escapes from the prefix. */ 239 pPrefix = sqlite3Expr(db, TK_STRING, (char*)z); 240 if( pPrefix ){ 241 int iFrom, iTo; 242 char *zNew = pPrefix->u.zToken; 243 zNew[cnt] = 0; 244 for(iFrom=iTo=0; iFrom<cnt; iFrom++){ 245 if( zNew[iFrom]==wc[3] ) iFrom++; 246 zNew[iTo++] = zNew[iFrom]; 247 } 248 zNew[iTo] = 0; 249 assert( iTo>0 ); 250 251 /* If the LHS is not an ordinary column with TEXT affinity, then the 252 ** pattern prefix boundaries (both the start and end boundaries) must 253 ** not look like a number. Otherwise the pattern might be treated as 254 ** a number, which will invalidate the LIKE optimization. 255 ** 256 ** Getting this right has been a persistent source of bugs in the 257 ** LIKE optimization. See, for example: 258 ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1 259 ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28 260 ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07 261 ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975 262 ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a 263 */ 264 if( pLeft->op!=TK_COLUMN 265 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 266 || IsVirtual(pLeft->y.pTab) /* Value might be numeric */ 267 ){ 268 int isNum; 269 double rDummy; 270 isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8); 271 if( isNum<=0 ){ 272 if( iTo==1 && zNew[0]=='-' ){ 273 isNum = +1; 274 }else{ 275 zNew[iTo-1]++; 276 isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8); 277 zNew[iTo-1]--; 278 } 279 } 280 if( isNum>0 ){ 281 sqlite3ExprDelete(db, pPrefix); 282 sqlite3ValueFree(pVal); 283 return 0; 284 } 285 } 286 } 287 *ppPrefix = pPrefix; 288 289 /* If the RHS pattern is a bound parameter, make arrangements to 290 ** reprepare the statement when that parameter is rebound */ 291 if( op==TK_VARIABLE ){ 292 Vdbe *v = pParse->pVdbe; 293 sqlite3VdbeSetVarmask(v, pRight->iColumn); 294 if( *pisComplete && pRight->u.zToken[1] ){ 295 /* If the rhs of the LIKE expression is a variable, and the current 296 ** value of the variable means there is no need to invoke the LIKE 297 ** function, then no OP_Variable will be added to the program. 298 ** This causes problems for the sqlite3_bind_parameter_name() 299 ** API. To work around them, add a dummy OP_Variable here. 300 */ 301 int r1 = sqlite3GetTempReg(pParse); 302 sqlite3ExprCodeTarget(pParse, pRight, r1); 303 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); 304 sqlite3ReleaseTempReg(pParse, r1); 305 } 306 } 307 }else{ 308 z = 0; 309 } 310 } 311 312 rc = (z!=0); 313 sqlite3ValueFree(pVal); 314 return rc; 315 } 316 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ 317 318 319 #ifndef SQLITE_OMIT_VIRTUALTABLE 320 /* 321 ** Check to see if the pExpr expression is a form that needs to be passed 322 ** to the xBestIndex method of virtual tables. Forms of interest include: 323 ** 324 ** Expression Virtual Table Operator 325 ** ----------------------- --------------------------------- 326 ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH 327 ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB 328 ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE 329 ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP 330 ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE 331 ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE 332 ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT 333 ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT 334 ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL 335 ** 336 ** In every case, "column" must be a column of a virtual table. If there 337 ** is a match, set *ppLeft to the "column" expression, set *ppRight to the 338 ** "expr" expression (even though in forms (6) and (8) the column is on the 339 ** right and the expression is on the left). Also set *peOp2 to the 340 ** appropriate virtual table operator. The return value is 1 or 2 if there 341 ** is a match. The usual return is 1, but if the RHS is also a column 342 ** of virtual table in forms (5) or (7) then return 2. 343 ** 344 ** If the expression matches none of the patterns above, return 0. 345 */ 346 static int isAuxiliaryVtabOperator( 347 sqlite3 *db, /* Parsing context */ 348 Expr *pExpr, /* Test this expression */ 349 unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */ 350 Expr **ppLeft, /* Column expression to left of MATCH/op2 */ 351 Expr **ppRight /* Expression to left of MATCH/op2 */ 352 ){ 353 if( pExpr->op==TK_FUNCTION ){ 354 static const struct Op2 { 355 const char *zOp; 356 unsigned char eOp2; 357 } aOp[] = { 358 { "match", SQLITE_INDEX_CONSTRAINT_MATCH }, 359 { "glob", SQLITE_INDEX_CONSTRAINT_GLOB }, 360 { "like", SQLITE_INDEX_CONSTRAINT_LIKE }, 361 { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP } 362 }; 363 ExprList *pList; 364 Expr *pCol; /* Column reference */ 365 int i; 366 367 pList = pExpr->x.pList; 368 if( pList==0 || pList->nExpr!=2 ){ 369 return 0; 370 } 371 372 /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a 373 ** virtual table on their second argument, which is the same as 374 ** the left-hand side operand in their in-fix form. 375 ** 376 ** vtab_column MATCH expression 377 ** MATCH(expression,vtab_column) 378 */ 379 pCol = pList->a[1].pExpr; 380 if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){ 381 for(i=0; i<ArraySize(aOp); i++){ 382 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){ 383 *peOp2 = aOp[i].eOp2; 384 *ppRight = pList->a[0].pExpr; 385 *ppLeft = pCol; 386 return 1; 387 } 388 } 389 } 390 391 /* We can also match against the first column of overloaded 392 ** functions where xFindFunction returns a value of at least 393 ** SQLITE_INDEX_CONSTRAINT_FUNCTION. 394 ** 395 ** OVERLOADED(vtab_column,expression) 396 ** 397 ** Historically, xFindFunction expected to see lower-case function 398 ** names. But for this use case, xFindFunction is expected to deal 399 ** with function names in an arbitrary case. 400 */ 401 pCol = pList->a[0].pExpr; 402 if( pCol->op==TK_COLUMN && IsVirtual(pCol->y.pTab) ){ 403 sqlite3_vtab *pVtab; 404 sqlite3_module *pMod; 405 void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**); 406 void *pNotUsed; 407 pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab; 408 assert( pVtab!=0 ); 409 assert( pVtab->pModule!=0 ); 410 pMod = (sqlite3_module *)pVtab->pModule; 411 if( pMod->xFindFunction!=0 ){ 412 i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed); 413 if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){ 414 *peOp2 = i; 415 *ppRight = pList->a[1].pExpr; 416 *ppLeft = pCol; 417 return 1; 418 } 419 } 420 } 421 }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){ 422 int res = 0; 423 Expr *pLeft = pExpr->pLeft; 424 Expr *pRight = pExpr->pRight; 425 if( pLeft->op==TK_COLUMN && IsVirtual(pLeft->y.pTab) ){ 426 res++; 427 } 428 if( pRight && pRight->op==TK_COLUMN && IsVirtual(pRight->y.pTab) ){ 429 res++; 430 SWAP(Expr*, pLeft, pRight); 431 } 432 *ppLeft = pLeft; 433 *ppRight = pRight; 434 if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE; 435 if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT; 436 if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL; 437 return res; 438 } 439 return 0; 440 } 441 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 442 443 /* 444 ** If the pBase expression originated in the ON or USING clause of 445 ** a join, then transfer the appropriate markings over to derived. 446 */ 447 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ 448 if( pDerived ){ 449 pDerived->flags |= pBase->flags & EP_FromJoin; 450 pDerived->iRightJoinTable = pBase->iRightJoinTable; 451 } 452 } 453 454 /* 455 ** Mark term iChild as being a child of term iParent 456 */ 457 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){ 458 pWC->a[iChild].iParent = iParent; 459 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb; 460 pWC->a[iParent].nChild++; 461 } 462 463 /* 464 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not 465 ** a conjunction, then return just pTerm when N==0. If N is exceeds 466 ** the number of available subterms, return NULL. 467 */ 468 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){ 469 if( pTerm->eOperator!=WO_AND ){ 470 return N==0 ? pTerm : 0; 471 } 472 if( N<pTerm->u.pAndInfo->wc.nTerm ){ 473 return &pTerm->u.pAndInfo->wc.a[N]; 474 } 475 return 0; 476 } 477 478 /* 479 ** Subterms pOne and pTwo are contained within WHERE clause pWC. The 480 ** two subterms are in disjunction - they are OR-ed together. 481 ** 482 ** If these two terms are both of the form: "A op B" with the same 483 ** A and B values but different operators and if the operators are 484 ** compatible (if one is = and the other is <, for example) then 485 ** add a new virtual AND term to pWC that is the combination of the 486 ** two. 487 ** 488 ** Some examples: 489 ** 490 ** x<y OR x=y --> x<=y 491 ** x=y OR x=y --> x=y 492 ** x<=y OR x<y --> x<=y 493 ** 494 ** The following is NOT generated: 495 ** 496 ** x<y OR x>y --> x!=y 497 */ 498 static void whereCombineDisjuncts( 499 SrcList *pSrc, /* the FROM clause */ 500 WhereClause *pWC, /* The complete WHERE clause */ 501 WhereTerm *pOne, /* First disjunct */ 502 WhereTerm *pTwo /* Second disjunct */ 503 ){ 504 u16 eOp = pOne->eOperator | pTwo->eOperator; 505 sqlite3 *db; /* Database connection (for malloc) */ 506 Expr *pNew; /* New virtual expression */ 507 int op; /* Operator for the combined expression */ 508 int idxNew; /* Index in pWC of the next virtual term */ 509 510 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; 511 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; 512 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp 513 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return; 514 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 ); 515 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 ); 516 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; 517 if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return; 518 /* If we reach this point, it means the two subterms can be combined */ 519 if( (eOp & (eOp-1))!=0 ){ 520 if( eOp & (WO_LT|WO_LE) ){ 521 eOp = WO_LE; 522 }else{ 523 assert( eOp & (WO_GT|WO_GE) ); 524 eOp = WO_GE; 525 } 526 } 527 db = pWC->pWInfo->pParse->db; 528 pNew = sqlite3ExprDup(db, pOne->pExpr, 0); 529 if( pNew==0 ) return; 530 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); } 531 pNew->op = op; 532 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); 533 exprAnalyze(pSrc, pWC, idxNew); 534 } 535 536 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) 537 /* 538 ** Analyze a term that consists of two or more OR-connected 539 ** subterms. So in: 540 ** 541 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) 542 ** ^^^^^^^^^^^^^^^^^^^^ 543 ** 544 ** This routine analyzes terms such as the middle term in the above example. 545 ** A WhereOrTerm object is computed and attached to the term under 546 ** analysis, regardless of the outcome of the analysis. Hence: 547 ** 548 ** WhereTerm.wtFlags |= TERM_ORINFO 549 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object 550 ** 551 ** The term being analyzed must have two or more of OR-connected subterms. 552 ** A single subterm might be a set of AND-connected sub-subterms. 553 ** Examples of terms under analysis: 554 ** 555 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 556 ** (B) x=expr1 OR expr2=x OR x=expr3 557 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) 558 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') 559 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) 560 ** (F) x>A OR (x=A AND y>=B) 561 ** 562 ** CASE 1: 563 ** 564 ** If all subterms are of the form T.C=expr for some single column of C and 565 ** a single table T (as shown in example B above) then create a new virtual 566 ** term that is an equivalent IN expression. In other words, if the term 567 ** being analyzed is: 568 ** 569 ** x = expr1 OR expr2 = x OR x = expr3 570 ** 571 ** then create a new virtual term like this: 572 ** 573 ** x IN (expr1,expr2,expr3) 574 ** 575 ** CASE 2: 576 ** 577 ** If there are exactly two disjuncts and one side has x>A and the other side 578 ** has x=A (for the same x and A) then add a new virtual conjunct term to the 579 ** WHERE clause of the form "x>=A". Example: 580 ** 581 ** x>A OR (x=A AND y>B) adds: x>=A 582 ** 583 ** The added conjunct can sometimes be helpful in query planning. 584 ** 585 ** CASE 3: 586 ** 587 ** If all subterms are indexable by a single table T, then set 588 ** 589 ** WhereTerm.eOperator = WO_OR 590 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T 591 ** 592 ** A subterm is "indexable" if it is of the form 593 ** "T.C <op> <expr>" where C is any column of table T and 594 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". 595 ** A subterm is also indexable if it is an AND of two or more 596 ** subsubterms at least one of which is indexable. Indexable AND 597 ** subterms have their eOperator set to WO_AND and they have 598 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object. 599 ** 600 ** From another point of view, "indexable" means that the subterm could 601 ** potentially be used with an index if an appropriate index exists. 602 ** This analysis does not consider whether or not the index exists; that 603 ** is decided elsewhere. This analysis only looks at whether subterms 604 ** appropriate for indexing exist. 605 ** 606 ** All examples A through E above satisfy case 3. But if a term 607 ** also satisfies case 1 (such as B) we know that the optimizer will 608 ** always prefer case 1, so in that case we pretend that case 3 is not 609 ** satisfied. 610 ** 611 ** It might be the case that multiple tables are indexable. For example, 612 ** (E) above is indexable on tables P, Q, and R. 613 ** 614 ** Terms that satisfy case 3 are candidates for lookup by using 615 ** separate indices to find rowids for each subterm and composing 616 ** the union of all rowids using a RowSet object. This is similar 617 ** to "bitmap indices" in other database engines. 618 ** 619 ** OTHERWISE: 620 ** 621 ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to 622 ** zero. This term is not useful for search. 623 */ 624 static void exprAnalyzeOrTerm( 625 SrcList *pSrc, /* the FROM clause */ 626 WhereClause *pWC, /* the complete WHERE clause */ 627 int idxTerm /* Index of the OR-term to be analyzed */ 628 ){ 629 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ 630 Parse *pParse = pWInfo->pParse; /* Parser context */ 631 sqlite3 *db = pParse->db; /* Database connection */ 632 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ 633 Expr *pExpr = pTerm->pExpr; /* The expression of the term */ 634 int i; /* Loop counters */ 635 WhereClause *pOrWc; /* Breakup of pTerm into subterms */ 636 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ 637 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ 638 Bitmask chngToIN; /* Tables that might satisfy case 1 */ 639 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ 640 641 /* 642 ** Break the OR clause into its separate subterms. The subterms are 643 ** stored in a WhereClause structure containing within the WhereOrInfo 644 ** object that is attached to the original OR clause term. 645 */ 646 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); 647 assert( pExpr->op==TK_OR ); 648 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); 649 if( pOrInfo==0 ) return; 650 pTerm->wtFlags |= TERM_ORINFO; 651 pOrWc = &pOrInfo->wc; 652 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic)); 653 sqlite3WhereClauseInit(pOrWc, pWInfo); 654 sqlite3WhereSplit(pOrWc, pExpr, TK_OR); 655 sqlite3WhereExprAnalyze(pSrc, pOrWc); 656 if( db->mallocFailed ) return; 657 assert( pOrWc->nTerm>=2 ); 658 659 /* 660 ** Compute the set of tables that might satisfy cases 1 or 3. 661 */ 662 indexable = ~(Bitmask)0; 663 chngToIN = ~(Bitmask)0; 664 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ 665 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ 666 WhereAndInfo *pAndInfo; 667 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); 668 chngToIN = 0; 669 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo)); 670 if( pAndInfo ){ 671 WhereClause *pAndWC; 672 WhereTerm *pAndTerm; 673 int j; 674 Bitmask b = 0; 675 pOrTerm->u.pAndInfo = pAndInfo; 676 pOrTerm->wtFlags |= TERM_ANDINFO; 677 pOrTerm->eOperator = WO_AND; 678 pAndWC = &pAndInfo->wc; 679 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic)); 680 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo); 681 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND); 682 sqlite3WhereExprAnalyze(pSrc, pAndWC); 683 pAndWC->pOuter = pWC; 684 if( !db->mallocFailed ){ 685 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){ 686 assert( pAndTerm->pExpr ); 687 if( allowedOp(pAndTerm->pExpr->op) 688 || pAndTerm->eOperator==WO_AUX 689 ){ 690 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); 691 } 692 } 693 } 694 indexable &= b; 695 } 696 }else if( pOrTerm->wtFlags & TERM_COPIED ){ 697 /* Skip this term for now. We revisit it when we process the 698 ** corresponding TERM_VIRTUAL term */ 699 }else{ 700 Bitmask b; 701 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); 702 if( pOrTerm->wtFlags & TERM_VIRTUAL ){ 703 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; 704 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor); 705 } 706 indexable &= b; 707 if( (pOrTerm->eOperator & WO_EQ)==0 ){ 708 chngToIN = 0; 709 }else{ 710 chngToIN &= b; 711 } 712 } 713 } 714 715 /* 716 ** Record the set of tables that satisfy case 3. The set might be 717 ** empty. 718 */ 719 pOrInfo->indexable = indexable; 720 if( indexable ){ 721 pTerm->eOperator = WO_OR; 722 pWC->hasOr = 1; 723 }else{ 724 pTerm->eOperator = WO_OR; 725 } 726 727 /* For a two-way OR, attempt to implementation case 2. 728 */ 729 if( indexable && pOrWc->nTerm==2 ){ 730 int iOne = 0; 731 WhereTerm *pOne; 732 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){ 733 int iTwo = 0; 734 WhereTerm *pTwo; 735 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){ 736 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo); 737 } 738 } 739 } 740 741 /* 742 ** chngToIN holds a set of tables that *might* satisfy case 1. But 743 ** we have to do some additional checking to see if case 1 really 744 ** is satisfied. 745 ** 746 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means 747 ** that there is no possibility of transforming the OR clause into an 748 ** IN operator because one or more terms in the OR clause contain 749 ** something other than == on a column in the single table. The 1-bit 750 ** case means that every term of the OR clause is of the form 751 ** "table.column=expr" for some single table. The one bit that is set 752 ** will correspond to the common table. We still need to check to make 753 ** sure the same column is used on all terms. The 2-bit case is when 754 ** the all terms are of the form "table1.column=table2.column". It 755 ** might be possible to form an IN operator with either table1.column 756 ** or table2.column as the LHS if either is common to every term of 757 ** the OR clause. 758 ** 759 ** Note that terms of the form "table.column1=table.column2" (the 760 ** same table on both sizes of the ==) cannot be optimized. 761 */ 762 if( chngToIN ){ 763 int okToChngToIN = 0; /* True if the conversion to IN is valid */ 764 int iColumn = -1; /* Column index on lhs of IN operator */ 765 int iCursor = -1; /* Table cursor common to all terms */ 766 int j = 0; /* Loop counter */ 767 768 /* Search for a table and column that appears on one side or the 769 ** other of the == operator in every subterm. That table and column 770 ** will be recorded in iCursor and iColumn. There might not be any 771 ** such table and column. Set okToChngToIN if an appropriate table 772 ** and column is found but leave okToChngToIN false if not found. 773 */ 774 for(j=0; j<2 && !okToChngToIN; j++){ 775 Expr *pLeft = 0; 776 pOrTerm = pOrWc->a; 777 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ 778 assert( pOrTerm->eOperator & WO_EQ ); 779 pOrTerm->wtFlags &= ~TERM_OR_OK; 780 if( pOrTerm->leftCursor==iCursor ){ 781 /* This is the 2-bit case and we are on the second iteration and 782 ** current term is from the first iteration. So skip this term. */ 783 assert( j==1 ); 784 continue; 785 } 786 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet, 787 pOrTerm->leftCursor))==0 ){ 788 /* This term must be of the form t1.a==t2.b where t2 is in the 789 ** chngToIN set but t1 is not. This term will be either preceded 790 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term 791 ** and use its inversion. */ 792 testcase( pOrTerm->wtFlags & TERM_COPIED ); 793 testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); 794 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); 795 continue; 796 } 797 iColumn = pOrTerm->u.leftColumn; 798 iCursor = pOrTerm->leftCursor; 799 pLeft = pOrTerm->pExpr->pLeft; 800 break; 801 } 802 if( i<0 ){ 803 /* No candidate table+column was found. This can only occur 804 ** on the second iteration */ 805 assert( j==1 ); 806 assert( IsPowerOfTwo(chngToIN) ); 807 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) ); 808 break; 809 } 810 testcase( j==1 ); 811 812 /* We have found a candidate table and column. Check to see if that 813 ** table and column is common to every term in the OR clause */ 814 okToChngToIN = 1; 815 for(; i>=0 && okToChngToIN; i--, pOrTerm++){ 816 assert( pOrTerm->eOperator & WO_EQ ); 817 if( pOrTerm->leftCursor!=iCursor ){ 818 pOrTerm->wtFlags &= ~TERM_OR_OK; 819 }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR 820 && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1) 821 )){ 822 okToChngToIN = 0; 823 }else{ 824 int affLeft, affRight; 825 /* If the right-hand side is also a column, then the affinities 826 ** of both right and left sides must be such that no type 827 ** conversions are required on the right. (Ticket #2249) 828 */ 829 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); 830 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); 831 if( affRight!=0 && affRight!=affLeft ){ 832 okToChngToIN = 0; 833 }else{ 834 pOrTerm->wtFlags |= TERM_OR_OK; 835 } 836 } 837 } 838 } 839 840 /* At this point, okToChngToIN is true if original pTerm satisfies 841 ** case 1. In that case, construct a new virtual term that is 842 ** pTerm converted into an IN operator. 843 */ 844 if( okToChngToIN ){ 845 Expr *pDup; /* A transient duplicate expression */ 846 ExprList *pList = 0; /* The RHS of the IN operator */ 847 Expr *pLeft = 0; /* The LHS of the IN operator */ 848 Expr *pNew; /* The complete IN operator */ 849 850 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ 851 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; 852 assert( pOrTerm->eOperator & WO_EQ ); 853 assert( pOrTerm->leftCursor==iCursor ); 854 assert( pOrTerm->u.leftColumn==iColumn ); 855 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); 856 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); 857 pLeft = pOrTerm->pExpr->pLeft; 858 } 859 assert( pLeft!=0 ); 860 pDup = sqlite3ExprDup(db, pLeft, 0); 861 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0); 862 if( pNew ){ 863 int idxNew; 864 transferJoinMarkings(pNew, pExpr); 865 assert( !ExprHasProperty(pNew, EP_xIsSelect) ); 866 pNew->x.pList = pList; 867 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); 868 testcase( idxNew==0 ); 869 exprAnalyze(pSrc, pWC, idxNew); 870 /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */ 871 markTermAsChild(pWC, idxNew, idxTerm); 872 }else{ 873 sqlite3ExprListDelete(db, pList); 874 } 875 } 876 } 877 } 878 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ 879 880 /* 881 ** We already know that pExpr is a binary operator where both operands are 882 ** column references. This routine checks to see if pExpr is an equivalence 883 ** relation: 884 ** 1. The SQLITE_Transitive optimization must be enabled 885 ** 2. Must be either an == or an IS operator 886 ** 3. Not originating in the ON clause of an OUTER JOIN 887 ** 4. The affinities of A and B must be compatible 888 ** 5a. Both operands use the same collating sequence OR 889 ** 5b. The overall collating sequence is BINARY 890 ** If this routine returns TRUE, that means that the RHS can be substituted 891 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs. 892 ** This is an optimization. No harm comes from returning 0. But if 1 is 893 ** returned when it should not be, then incorrect answers might result. 894 */ 895 static int termIsEquivalence(Parse *pParse, Expr *pExpr){ 896 char aff1, aff2; 897 CollSeq *pColl; 898 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; 899 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; 900 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0; 901 aff1 = sqlite3ExprAffinity(pExpr->pLeft); 902 aff2 = sqlite3ExprAffinity(pExpr->pRight); 903 if( aff1!=aff2 904 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2)) 905 ){ 906 return 0; 907 } 908 pColl = sqlite3ExprCompareCollSeq(pParse, pExpr); 909 if( sqlite3IsBinary(pColl) ) return 1; 910 return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight); 911 } 912 913 /* 914 ** Recursively walk the expressions of a SELECT statement and generate 915 ** a bitmask indicating which tables are used in that expression 916 ** tree. 917 */ 918 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ 919 Bitmask mask = 0; 920 while( pS ){ 921 SrcList *pSrc = pS->pSrc; 922 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList); 923 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy); 924 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy); 925 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere); 926 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving); 927 if( ALWAYS(pSrc!=0) ){ 928 int i; 929 for(i=0; i<pSrc->nSrc; i++){ 930 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect); 931 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn); 932 if( pSrc->a[i].fg.isTabFunc ){ 933 mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg); 934 } 935 } 936 } 937 pS = pS->pPrior; 938 } 939 return mask; 940 } 941 942 /* 943 ** Expression pExpr is one operand of a comparison operator that might 944 ** be useful for indexing. This routine checks to see if pExpr appears 945 ** in any index. Return TRUE (1) if pExpr is an indexed term and return 946 ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor 947 ** number of the table that is indexed and aiCurCol[1] to the column number 948 ** of the column that is indexed, or XN_EXPR (-2) if an expression is being 949 ** indexed. 950 ** 951 ** If pExpr is a TK_COLUMN column reference, then this routine always returns 952 ** true even if that particular column is not indexed, because the column 953 ** might be added to an automatic index later. 954 */ 955 static SQLITE_NOINLINE int exprMightBeIndexed2( 956 SrcList *pFrom, /* The FROM clause */ 957 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ 958 int *aiCurCol, /* Write the referenced table cursor and column here */ 959 Expr *pExpr /* An operand of a comparison operator */ 960 ){ 961 Index *pIdx; 962 int i; 963 int iCur; 964 for(i=0; mPrereq>1; i++, mPrereq>>=1){} 965 iCur = pFrom->a[i].iCursor; 966 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 967 if( pIdx->aColExpr==0 ) continue; 968 for(i=0; i<pIdx->nKeyCol; i++){ 969 if( pIdx->aiColumn[i]!=XN_EXPR ) continue; 970 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){ 971 aiCurCol[0] = iCur; 972 aiCurCol[1] = XN_EXPR; 973 return 1; 974 } 975 } 976 } 977 return 0; 978 } 979 static int exprMightBeIndexed( 980 SrcList *pFrom, /* The FROM clause */ 981 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ 982 int *aiCurCol, /* Write the referenced table cursor & column here */ 983 Expr *pExpr, /* An operand of a comparison operator */ 984 int op /* The specific comparison operator */ 985 ){ 986 /* If this expression is a vector to the left or right of a 987 ** inequality constraint (>, <, >= or <=), perform the processing 988 ** on the first element of the vector. */ 989 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE ); 990 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE ); 991 assert( op<=TK_GE ); 992 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){ 993 pExpr = pExpr->x.pList->a[0].pExpr; 994 } 995 996 if( pExpr->op==TK_COLUMN ){ 997 aiCurCol[0] = pExpr->iTable; 998 aiCurCol[1] = pExpr->iColumn; 999 return 1; 1000 } 1001 if( mPrereq==0 ) return 0; /* No table references */ 1002 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */ 1003 return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr); 1004 } 1005 1006 /* 1007 ** The input to this routine is an WhereTerm structure with only the 1008 ** "pExpr" field filled in. The job of this routine is to analyze the 1009 ** subexpression and populate all the other fields of the WhereTerm 1010 ** structure. 1011 ** 1012 ** If the expression is of the form "<expr> <op> X" it gets commuted 1013 ** to the standard form of "X <op> <expr>". 1014 ** 1015 ** If the expression is of the form "X <op> Y" where both X and Y are 1016 ** columns, then the original expression is unchanged and a new virtual 1017 ** term of the form "Y <op> X" is added to the WHERE clause and 1018 ** analyzed separately. The original term is marked with TERM_COPIED 1019 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr 1020 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it 1021 ** is a commuted copy of a prior term.) The original term has nChild=1 1022 ** and the copy has idxParent set to the index of the original term. 1023 */ 1024 static void exprAnalyze( 1025 SrcList *pSrc, /* the FROM clause */ 1026 WhereClause *pWC, /* the WHERE clause */ 1027 int idxTerm /* Index of the term to be analyzed */ 1028 ){ 1029 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ 1030 WhereTerm *pTerm; /* The term to be analyzed */ 1031 WhereMaskSet *pMaskSet; /* Set of table index masks */ 1032 Expr *pExpr; /* The expression to be analyzed */ 1033 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ 1034 Bitmask prereqAll; /* Prerequesites of pExpr */ 1035 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ 1036 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ 1037 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ 1038 int noCase = 0; /* uppercase equivalent to lowercase */ 1039 int op; /* Top-level operator. pExpr->op */ 1040 Parse *pParse = pWInfo->pParse; /* Parsing context */ 1041 sqlite3 *db = pParse->db; /* Database connection */ 1042 unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */ 1043 int nLeft; /* Number of elements on left side vector */ 1044 1045 if( db->mallocFailed ){ 1046 return; 1047 } 1048 pTerm = &pWC->a[idxTerm]; 1049 pMaskSet = &pWInfo->sMaskSet; 1050 pExpr = pTerm->pExpr; 1051 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); 1052 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); 1053 op = pExpr->op; 1054 if( op==TK_IN ){ 1055 assert( pExpr->pRight==0 ); 1056 if( sqlite3ExprCheckIN(pParse, pExpr) ) return; 1057 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 1058 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect); 1059 }else{ 1060 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList); 1061 } 1062 }else if( op==TK_ISNULL ){ 1063 pTerm->prereqRight = 0; 1064 }else{ 1065 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight); 1066 } 1067 pMaskSet->bVarSelect = 0; 1068 prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr); 1069 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT; 1070 if( ExprHasProperty(pExpr, EP_FromJoin) ){ 1071 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable); 1072 prereqAll |= x; 1073 extraRight = x-1; /* ON clause terms may not be used with an index 1074 ** on left table of a LEFT JOIN. Ticket #3015 */ 1075 if( (prereqAll>>1)>=x ){ 1076 sqlite3ErrorMsg(pParse, "ON clause references tables to its right"); 1077 return; 1078 } 1079 } 1080 pTerm->prereqAll = prereqAll; 1081 pTerm->leftCursor = -1; 1082 pTerm->iParent = -1; 1083 pTerm->eOperator = 0; 1084 if( allowedOp(op) ){ 1085 int aiCurCol[2]; 1086 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); 1087 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); 1088 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; 1089 1090 if( pTerm->iField>0 ){ 1091 assert( op==TK_IN ); 1092 assert( pLeft->op==TK_VECTOR ); 1093 pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr; 1094 } 1095 1096 if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){ 1097 pTerm->leftCursor = aiCurCol[0]; 1098 pTerm->u.leftColumn = aiCurCol[1]; 1099 pTerm->eOperator = operatorMask(op) & opMask; 1100 } 1101 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS; 1102 if( pRight 1103 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op) 1104 ){ 1105 WhereTerm *pNew; 1106 Expr *pDup; 1107 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ 1108 assert( pTerm->iField==0 ); 1109 if( pTerm->leftCursor>=0 ){ 1110 int idxNew; 1111 pDup = sqlite3ExprDup(db, pExpr, 0); 1112 if( db->mallocFailed ){ 1113 sqlite3ExprDelete(db, pDup); 1114 return; 1115 } 1116 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); 1117 if( idxNew==0 ) return; 1118 pNew = &pWC->a[idxNew]; 1119 markTermAsChild(pWC, idxNew, idxTerm); 1120 if( op==TK_IS ) pNew->wtFlags |= TERM_IS; 1121 pTerm = &pWC->a[idxTerm]; 1122 pTerm->wtFlags |= TERM_COPIED; 1123 1124 if( termIsEquivalence(pParse, pDup) ){ 1125 pTerm->eOperator |= WO_EQUIV; 1126 eExtraOp = WO_EQUIV; 1127 } 1128 }else{ 1129 pDup = pExpr; 1130 pNew = pTerm; 1131 } 1132 pNew->wtFlags |= exprCommute(pParse, pDup); 1133 pNew->leftCursor = aiCurCol[0]; 1134 pNew->u.leftColumn = aiCurCol[1]; 1135 testcase( (prereqLeft | extraRight) != prereqLeft ); 1136 pNew->prereqRight = prereqLeft | extraRight; 1137 pNew->prereqAll = prereqAll; 1138 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask; 1139 } 1140 } 1141 1142 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION 1143 /* If a term is the BETWEEN operator, create two new virtual terms 1144 ** that define the range that the BETWEEN implements. For example: 1145 ** 1146 ** a BETWEEN b AND c 1147 ** 1148 ** is converted into: 1149 ** 1150 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) 1151 ** 1152 ** The two new terms are added onto the end of the WhereClause object. 1153 ** The new terms are "dynamic" and are children of the original BETWEEN 1154 ** term. That means that if the BETWEEN term is coded, the children are 1155 ** skipped. Or, if the children are satisfied by an index, the original 1156 ** BETWEEN term is skipped. 1157 */ 1158 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ 1159 ExprList *pList = pExpr->x.pList; 1160 int i; 1161 static const u8 ops[] = {TK_GE, TK_LE}; 1162 assert( pList!=0 ); 1163 assert( pList->nExpr==2 ); 1164 for(i=0; i<2; i++){ 1165 Expr *pNewExpr; 1166 int idxNew; 1167 pNewExpr = sqlite3PExpr(pParse, ops[i], 1168 sqlite3ExprDup(db, pExpr->pLeft, 0), 1169 sqlite3ExprDup(db, pList->a[i].pExpr, 0)); 1170 transferJoinMarkings(pNewExpr, pExpr); 1171 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); 1172 testcase( idxNew==0 ); 1173 exprAnalyze(pSrc, pWC, idxNew); 1174 pTerm = &pWC->a[idxTerm]; 1175 markTermAsChild(pWC, idxNew, idxTerm); 1176 } 1177 } 1178 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ 1179 1180 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) 1181 /* Analyze a term that is composed of two or more subterms connected by 1182 ** an OR operator. 1183 */ 1184 else if( pExpr->op==TK_OR ){ 1185 assert( pWC->op==TK_AND ); 1186 exprAnalyzeOrTerm(pSrc, pWC, idxTerm); 1187 pTerm = &pWC->a[idxTerm]; 1188 } 1189 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 1190 1191 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION 1192 /* Add constraints to reduce the search space on a LIKE or GLOB 1193 ** operator. 1194 ** 1195 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints 1196 ** 1197 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%' 1198 ** 1199 ** The last character of the prefix "abc" is incremented to form the 1200 ** termination condition "abd". If case is not significant (the default 1201 ** for LIKE) then the lower-bound is made all uppercase and the upper- 1202 ** bound is made all lowercase so that the bounds also work when comparing 1203 ** BLOBs. 1204 */ 1205 if( pWC->op==TK_AND 1206 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) 1207 ){ 1208 Expr *pLeft; /* LHS of LIKE/GLOB operator */ 1209 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ 1210 Expr *pNewExpr1; 1211 Expr *pNewExpr2; 1212 int idxNew1; 1213 int idxNew2; 1214 const char *zCollSeqName; /* Name of collating sequence */ 1215 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC; 1216 1217 pLeft = pExpr->x.pList->a[1].pExpr; 1218 pStr2 = sqlite3ExprDup(db, pStr1, 0); 1219 1220 /* Convert the lower bound to upper-case and the upper bound to 1221 ** lower-case (upper-case is less than lower-case in ASCII) so that 1222 ** the range constraints also work for BLOBs 1223 */ 1224 if( noCase && !pParse->db->mallocFailed ){ 1225 int i; 1226 char c; 1227 pTerm->wtFlags |= TERM_LIKE; 1228 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){ 1229 pStr1->u.zToken[i] = sqlite3Toupper(c); 1230 pStr2->u.zToken[i] = sqlite3Tolower(c); 1231 } 1232 } 1233 1234 if( !db->mallocFailed ){ 1235 u8 c, *pC; /* Last character before the first wildcard */ 1236 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; 1237 c = *pC; 1238 if( noCase ){ 1239 /* The point is to increment the last character before the first 1240 ** wildcard. But if we increment '@', that will push it into the 1241 ** alphabetic range where case conversions will mess up the 1242 ** inequality. To avoid this, make sure to also run the full 1243 ** LIKE on all candidate expressions by clearing the isComplete flag 1244 */ 1245 if( c=='A'-1 ) isComplete = 0; 1246 c = sqlite3UpperToLower[c]; 1247 } 1248 *pC = c + 1; 1249 } 1250 zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY; 1251 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); 1252 pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 1253 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName), 1254 pStr1); 1255 transferJoinMarkings(pNewExpr1, pExpr); 1256 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags); 1257 testcase( idxNew1==0 ); 1258 exprAnalyze(pSrc, pWC, idxNew1); 1259 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); 1260 pNewExpr2 = sqlite3PExpr(pParse, TK_LT, 1261 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), 1262 pStr2); 1263 transferJoinMarkings(pNewExpr2, pExpr); 1264 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags); 1265 testcase( idxNew2==0 ); 1266 exprAnalyze(pSrc, pWC, idxNew2); 1267 pTerm = &pWC->a[idxTerm]; 1268 if( isComplete ){ 1269 markTermAsChild(pWC, idxNew1, idxTerm); 1270 markTermAsChild(pWC, idxNew2, idxTerm); 1271 } 1272 } 1273 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ 1274 1275 #ifndef SQLITE_OMIT_VIRTUALTABLE 1276 /* Add a WO_AUX auxiliary term to the constraint set if the 1277 ** current expression is of the form "column OP expr" where OP 1278 ** is an operator that gets passed into virtual tables but which is 1279 ** not normally optimized for ordinary tables. In other words, OP 1280 ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL. 1281 ** This information is used by the xBestIndex methods of 1282 ** virtual tables. The native query optimizer does not attempt 1283 ** to do anything with MATCH functions. 1284 */ 1285 if( pWC->op==TK_AND ){ 1286 Expr *pRight = 0, *pLeft = 0; 1287 int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight); 1288 while( res-- > 0 ){ 1289 int idxNew; 1290 WhereTerm *pNewTerm; 1291 Bitmask prereqColumn, prereqExpr; 1292 1293 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight); 1294 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft); 1295 if( (prereqExpr & prereqColumn)==0 ){ 1296 Expr *pNewExpr; 1297 pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 1298 0, sqlite3ExprDup(db, pRight, 0)); 1299 if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){ 1300 ExprSetProperty(pNewExpr, EP_FromJoin); 1301 } 1302 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); 1303 testcase( idxNew==0 ); 1304 pNewTerm = &pWC->a[idxNew]; 1305 pNewTerm->prereqRight = prereqExpr; 1306 pNewTerm->leftCursor = pLeft->iTable; 1307 pNewTerm->u.leftColumn = pLeft->iColumn; 1308 pNewTerm->eOperator = WO_AUX; 1309 pNewTerm->eMatchOp = eOp2; 1310 markTermAsChild(pWC, idxNew, idxTerm); 1311 pTerm = &pWC->a[idxTerm]; 1312 pTerm->wtFlags |= TERM_COPIED; 1313 pNewTerm->prereqAll = pTerm->prereqAll; 1314 } 1315 SWAP(Expr*, pLeft, pRight); 1316 } 1317 } 1318 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 1319 1320 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create 1321 ** new terms for each component comparison - "a = ?" and "b = ?". The 1322 ** new terms completely replace the original vector comparison, which is 1323 ** no longer used. 1324 ** 1325 ** This is only required if at least one side of the comparison operation 1326 ** is not a sub-select. */ 1327 if( pWC->op==TK_AND 1328 && (pExpr->op==TK_EQ || pExpr->op==TK_IS) 1329 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1 1330 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft 1331 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 1332 || (pExpr->pRight->flags & EP_xIsSelect)==0) 1333 ){ 1334 int i; 1335 for(i=0; i<nLeft; i++){ 1336 int idxNew; 1337 Expr *pNew; 1338 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i); 1339 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i); 1340 1341 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight); 1342 transferJoinMarkings(pNew, pExpr); 1343 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC); 1344 exprAnalyze(pSrc, pWC, idxNew); 1345 } 1346 pTerm = &pWC->a[idxTerm]; 1347 pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */ 1348 pTerm->eOperator = 0; 1349 } 1350 1351 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create 1352 ** a virtual term for each vector component. The expression object 1353 ** used by each such virtual term is pExpr (the full vector IN(...) 1354 ** expression). The WhereTerm.iField variable identifies the index within 1355 ** the vector on the LHS that the virtual term represents. 1356 ** 1357 ** This only works if the RHS is a simple SELECT, not a compound 1358 */ 1359 if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0 1360 && pExpr->pLeft->op==TK_VECTOR 1361 && pExpr->x.pSelect->pPrior==0 1362 ){ 1363 int i; 1364 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){ 1365 int idxNew; 1366 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL); 1367 pWC->a[idxNew].iField = i+1; 1368 exprAnalyze(pSrc, pWC, idxNew); 1369 markTermAsChild(pWC, idxNew, idxTerm); 1370 } 1371 } 1372 1373 #ifdef SQLITE_ENABLE_STAT4 1374 /* When sqlite_stat4 histogram data is available an operator of the 1375 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently 1376 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a 1377 ** virtual term of that form. 1378 ** 1379 ** Note that the virtual term must be tagged with TERM_VNULL. 1380 */ 1381 if( pExpr->op==TK_NOTNULL 1382 && pExpr->pLeft->op==TK_COLUMN 1383 && pExpr->pLeft->iColumn>=0 1384 && !ExprHasProperty(pExpr, EP_FromJoin) 1385 && OptimizationEnabled(db, SQLITE_Stat4) 1386 ){ 1387 Expr *pNewExpr; 1388 Expr *pLeft = pExpr->pLeft; 1389 int idxNew; 1390 WhereTerm *pNewTerm; 1391 1392 pNewExpr = sqlite3PExpr(pParse, TK_GT, 1393 sqlite3ExprDup(db, pLeft, 0), 1394 sqlite3ExprAlloc(db, TK_NULL, 0, 0)); 1395 1396 idxNew = whereClauseInsert(pWC, pNewExpr, 1397 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); 1398 if( idxNew ){ 1399 pNewTerm = &pWC->a[idxNew]; 1400 pNewTerm->prereqRight = 0; 1401 pNewTerm->leftCursor = pLeft->iTable; 1402 pNewTerm->u.leftColumn = pLeft->iColumn; 1403 pNewTerm->eOperator = WO_GT; 1404 markTermAsChild(pWC, idxNew, idxTerm); 1405 pTerm = &pWC->a[idxTerm]; 1406 pTerm->wtFlags |= TERM_COPIED; 1407 pNewTerm->prereqAll = pTerm->prereqAll; 1408 } 1409 } 1410 #endif /* SQLITE_ENABLE_STAT4 */ 1411 1412 /* Prevent ON clause terms of a LEFT JOIN from being used to drive 1413 ** an index for tables to the left of the join. 1414 */ 1415 testcase( pTerm!=&pWC->a[idxTerm] ); 1416 pTerm = &pWC->a[idxTerm]; 1417 pTerm->prereqRight |= extraRight; 1418 } 1419 1420 /*************************************************************************** 1421 ** Routines with file scope above. Interface to the rest of the where.c 1422 ** subsystem follows. 1423 ***************************************************************************/ 1424 1425 /* 1426 ** This routine identifies subexpressions in the WHERE clause where 1427 ** each subexpression is separated by the AND operator or some other 1428 ** operator specified in the op parameter. The WhereClause structure 1429 ** is filled with pointers to subexpressions. For example: 1430 ** 1431 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) 1432 ** \________/ \_______________/ \________________/ 1433 ** slot[0] slot[1] slot[2] 1434 ** 1435 ** The original WHERE clause in pExpr is unaltered. All this routine 1436 ** does is make slot[] entries point to substructure within pExpr. 1437 ** 1438 ** In the previous sentence and in the diagram, "slot[]" refers to 1439 ** the WhereClause.a[] array. The slot[] array grows as needed to contain 1440 ** all terms of the WHERE clause. 1441 */ 1442 void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ 1443 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr); 1444 pWC->op = op; 1445 if( pE2==0 ) return; 1446 if( pE2->op!=op ){ 1447 whereClauseInsert(pWC, pExpr, 0); 1448 }else{ 1449 sqlite3WhereSplit(pWC, pE2->pLeft, op); 1450 sqlite3WhereSplit(pWC, pE2->pRight, op); 1451 } 1452 } 1453 1454 /* 1455 ** Initialize a preallocated WhereClause structure. 1456 */ 1457 void sqlite3WhereClauseInit( 1458 WhereClause *pWC, /* The WhereClause to be initialized */ 1459 WhereInfo *pWInfo /* The WHERE processing context */ 1460 ){ 1461 pWC->pWInfo = pWInfo; 1462 pWC->hasOr = 0; 1463 pWC->pOuter = 0; 1464 pWC->nTerm = 0; 1465 pWC->nSlot = ArraySize(pWC->aStatic); 1466 pWC->a = pWC->aStatic; 1467 } 1468 1469 /* 1470 ** Deallocate a WhereClause structure. The WhereClause structure 1471 ** itself is not freed. This routine is the inverse of 1472 ** sqlite3WhereClauseInit(). 1473 */ 1474 void sqlite3WhereClauseClear(WhereClause *pWC){ 1475 int i; 1476 WhereTerm *a; 1477 sqlite3 *db = pWC->pWInfo->pParse->db; 1478 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ 1479 if( a->wtFlags & TERM_DYNAMIC ){ 1480 sqlite3ExprDelete(db, a->pExpr); 1481 } 1482 if( a->wtFlags & TERM_ORINFO ){ 1483 whereOrInfoDelete(db, a->u.pOrInfo); 1484 }else if( a->wtFlags & TERM_ANDINFO ){ 1485 whereAndInfoDelete(db, a->u.pAndInfo); 1486 } 1487 } 1488 if( pWC->a!=pWC->aStatic ){ 1489 sqlite3DbFree(db, pWC->a); 1490 } 1491 } 1492 1493 1494 /* 1495 ** These routines walk (recursively) an expression tree and generate 1496 ** a bitmask indicating which tables are used in that expression 1497 ** tree. 1498 */ 1499 Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){ 1500 Bitmask mask; 1501 if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){ 1502 return sqlite3WhereGetMask(pMaskSet, p->iTable); 1503 }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ 1504 assert( p->op!=TK_IF_NULL_ROW ); 1505 return 0; 1506 } 1507 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0; 1508 if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft); 1509 if( p->pRight ){ 1510 mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight); 1511 assert( p->x.pList==0 ); 1512 }else if( ExprHasProperty(p, EP_xIsSelect) ){ 1513 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1; 1514 mask |= exprSelectUsage(pMaskSet, p->x.pSelect); 1515 }else if( p->x.pList ){ 1516 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList); 1517 } 1518 #ifndef SQLITE_OMIT_WINDOWFUNC 1519 if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){ 1520 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition); 1521 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy); 1522 mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter); 1523 } 1524 #endif 1525 return mask; 1526 } 1527 Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ 1528 return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0; 1529 } 1530 Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){ 1531 int i; 1532 Bitmask mask = 0; 1533 if( pList ){ 1534 for(i=0; i<pList->nExpr; i++){ 1535 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr); 1536 } 1537 } 1538 return mask; 1539 } 1540 1541 1542 /* 1543 ** Call exprAnalyze on all terms in a WHERE clause. 1544 ** 1545 ** Note that exprAnalyze() might add new virtual terms onto the 1546 ** end of the WHERE clause. We do not want to analyze these new 1547 ** virtual terms, so start analyzing at the end and work forward 1548 ** so that the added virtual terms are never processed. 1549 */ 1550 void sqlite3WhereExprAnalyze( 1551 SrcList *pTabList, /* the FROM clause */ 1552 WhereClause *pWC /* the WHERE clause to be analyzed */ 1553 ){ 1554 int i; 1555 for(i=pWC->nTerm-1; i>=0; i--){ 1556 exprAnalyze(pTabList, pWC, i); 1557 } 1558 } 1559 1560 /* 1561 ** For table-valued-functions, transform the function arguments into 1562 ** new WHERE clause terms. 1563 ** 1564 ** Each function argument translates into an equality constraint against 1565 ** a HIDDEN column in the table. 1566 */ 1567 void sqlite3WhereTabFuncArgs( 1568 Parse *pParse, /* Parsing context */ 1569 struct SrcList_item *pItem, /* The FROM clause term to process */ 1570 WhereClause *pWC /* Xfer function arguments to here */ 1571 ){ 1572 Table *pTab; 1573 int j, k; 1574 ExprList *pArgs; 1575 Expr *pColRef; 1576 Expr *pTerm; 1577 if( pItem->fg.isTabFunc==0 ) return; 1578 pTab = pItem->pTab; 1579 assert( pTab!=0 ); 1580 pArgs = pItem->u1.pFuncArg; 1581 if( pArgs==0 ) return; 1582 for(j=k=0; j<pArgs->nExpr; j++){ 1583 Expr *pRhs; 1584 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;} 1585 if( k>=pTab->nCol ){ 1586 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d", 1587 pTab->zName, j); 1588 return; 1589 } 1590 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); 1591 if( pColRef==0 ) return; 1592 pColRef->iTable = pItem->iCursor; 1593 pColRef->iColumn = k++; 1594 pColRef->y.pTab = pTab; 1595 pRhs = sqlite3PExpr(pParse, TK_UPLUS, 1596 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0); 1597 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs); 1598 if( pItem->fg.jointype & JT_LEFT ){ 1599 sqlite3SetJoinExpr(pTerm, pItem->iCursor); 1600 } 1601 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC); 1602 } 1603 } 1604