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