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 testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 ); 381 if( ExprIsVtab(pCol) ){ 382 for(i=0; i<ArraySize(aOp); i++){ 383 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){ 384 *peOp2 = aOp[i].eOp2; 385 *ppRight = pList->a[0].pExpr; 386 *ppLeft = pCol; 387 return 1; 388 } 389 } 390 } 391 392 /* We can also match against the first column of overloaded 393 ** functions where xFindFunction returns a value of at least 394 ** SQLITE_INDEX_CONSTRAINT_FUNCTION. 395 ** 396 ** OVERLOADED(vtab_column,expression) 397 ** 398 ** Historically, xFindFunction expected to see lower-case function 399 ** names. But for this use case, xFindFunction is expected to deal 400 ** with function names in an arbitrary case. 401 */ 402 pCol = pList->a[0].pExpr; 403 testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 ); 404 if( ExprIsVtab(pCol) ){ 405 sqlite3_vtab *pVtab; 406 sqlite3_module *pMod; 407 void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**); 408 void *pNotUsed; 409 pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab; 410 assert( pVtab!=0 ); 411 assert( pVtab->pModule!=0 ); 412 pMod = (sqlite3_module *)pVtab->pModule; 413 if( pMod->xFindFunction!=0 ){ 414 i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed); 415 if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){ 416 *peOp2 = i; 417 *ppRight = pList->a[1].pExpr; 418 *ppLeft = pCol; 419 return 1; 420 } 421 } 422 } 423 }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){ 424 int res = 0; 425 Expr *pLeft = pExpr->pLeft; 426 Expr *pRight = pExpr->pRight; 427 testcase( pLeft->op==TK_COLUMN && pLeft->y.pTab==0 ); 428 if( ExprIsVtab(pLeft) ){ 429 res++; 430 } 431 testcase( pRight && pRight->op==TK_COLUMN && pRight->y.pTab==0 ); 432 if( pRight && ExprIsVtab(pRight) ){ 433 res++; 434 SWAP(Expr*, pLeft, pRight); 435 } 436 *ppLeft = pLeft; 437 *ppRight = pRight; 438 if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE; 439 if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT; 440 if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL; 441 return res; 442 } 443 return 0; 444 } 445 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 446 447 /* 448 ** If the pBase expression originated in the ON or USING clause of 449 ** a join, then transfer the appropriate markings over to derived. 450 */ 451 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ 452 if( pDerived ){ 453 pDerived->flags |= pBase->flags & EP_FromJoin; 454 pDerived->iRightJoinTable = pBase->iRightJoinTable; 455 } 456 } 457 458 /* 459 ** Mark term iChild as being a child of term iParent 460 */ 461 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){ 462 pWC->a[iChild].iParent = iParent; 463 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb; 464 pWC->a[iParent].nChild++; 465 } 466 467 /* 468 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not 469 ** a conjunction, then return just pTerm when N==0. If N is exceeds 470 ** the number of available subterms, return NULL. 471 */ 472 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){ 473 if( pTerm->eOperator!=WO_AND ){ 474 return N==0 ? pTerm : 0; 475 } 476 if( N<pTerm->u.pAndInfo->wc.nTerm ){ 477 return &pTerm->u.pAndInfo->wc.a[N]; 478 } 479 return 0; 480 } 481 482 /* 483 ** Subterms pOne and pTwo are contained within WHERE clause pWC. The 484 ** two subterms are in disjunction - they are OR-ed together. 485 ** 486 ** If these two terms are both of the form: "A op B" with the same 487 ** A and B values but different operators and if the operators are 488 ** compatible (if one is = and the other is <, for example) then 489 ** add a new virtual AND term to pWC that is the combination of the 490 ** two. 491 ** 492 ** Some examples: 493 ** 494 ** x<y OR x=y --> x<=y 495 ** x=y OR x=y --> x=y 496 ** x<=y OR x<y --> x<=y 497 ** 498 ** The following is NOT generated: 499 ** 500 ** x<y OR x>y --> x!=y 501 */ 502 static void whereCombineDisjuncts( 503 SrcList *pSrc, /* the FROM clause */ 504 WhereClause *pWC, /* The complete WHERE clause */ 505 WhereTerm *pOne, /* First disjunct */ 506 WhereTerm *pTwo /* Second disjunct */ 507 ){ 508 u16 eOp = pOne->eOperator | pTwo->eOperator; 509 sqlite3 *db; /* Database connection (for malloc) */ 510 Expr *pNew; /* New virtual expression */ 511 int op; /* Operator for the combined expression */ 512 int idxNew; /* Index in pWC of the next virtual term */ 513 514 if( (pOne->wtFlags | pTwo->wtFlags) & TERM_VNULL ) return; 515 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; 516 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return; 517 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp 518 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return; 519 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 ); 520 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 ); 521 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return; 522 if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return; 523 /* If we reach this point, it means the two subterms can be combined */ 524 if( (eOp & (eOp-1))!=0 ){ 525 if( eOp & (WO_LT|WO_LE) ){ 526 eOp = WO_LE; 527 }else{ 528 assert( eOp & (WO_GT|WO_GE) ); 529 eOp = WO_GE; 530 } 531 } 532 db = pWC->pWInfo->pParse->db; 533 pNew = sqlite3ExprDup(db, pOne->pExpr, 0); 534 if( pNew==0 ) return; 535 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); } 536 pNew->op = op; 537 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); 538 exprAnalyze(pSrc, pWC, idxNew); 539 } 540 541 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) 542 /* 543 ** Analyze a term that consists of two or more OR-connected 544 ** subterms. So in: 545 ** 546 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) 547 ** ^^^^^^^^^^^^^^^^^^^^ 548 ** 549 ** This routine analyzes terms such as the middle term in the above example. 550 ** A WhereOrTerm object is computed and attached to the term under 551 ** analysis, regardless of the outcome of the analysis. Hence: 552 ** 553 ** WhereTerm.wtFlags |= TERM_ORINFO 554 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object 555 ** 556 ** The term being analyzed must have two or more of OR-connected subterms. 557 ** A single subterm might be a set of AND-connected sub-subterms. 558 ** Examples of terms under analysis: 559 ** 560 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 561 ** (B) x=expr1 OR expr2=x OR x=expr3 562 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) 563 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') 564 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) 565 ** (F) x>A OR (x=A AND y>=B) 566 ** 567 ** CASE 1: 568 ** 569 ** If all subterms are of the form T.C=expr for some single column of C and 570 ** a single table T (as shown in example B above) then create a new virtual 571 ** term that is an equivalent IN expression. In other words, if the term 572 ** being analyzed is: 573 ** 574 ** x = expr1 OR expr2 = x OR x = expr3 575 ** 576 ** then create a new virtual term like this: 577 ** 578 ** x IN (expr1,expr2,expr3) 579 ** 580 ** CASE 2: 581 ** 582 ** If there are exactly two disjuncts and one side has x>A and the other side 583 ** has x=A (for the same x and A) then add a new virtual conjunct term to the 584 ** WHERE clause of the form "x>=A". Example: 585 ** 586 ** x>A OR (x=A AND y>B) adds: x>=A 587 ** 588 ** The added conjunct can sometimes be helpful in query planning. 589 ** 590 ** CASE 3: 591 ** 592 ** If all subterms are indexable by a single table T, then set 593 ** 594 ** WhereTerm.eOperator = WO_OR 595 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T 596 ** 597 ** A subterm is "indexable" if it is of the form 598 ** "T.C <op> <expr>" where C is any column of table T and 599 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". 600 ** A subterm is also indexable if it is an AND of two or more 601 ** subsubterms at least one of which is indexable. Indexable AND 602 ** subterms have their eOperator set to WO_AND and they have 603 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object. 604 ** 605 ** From another point of view, "indexable" means that the subterm could 606 ** potentially be used with an index if an appropriate index exists. 607 ** This analysis does not consider whether or not the index exists; that 608 ** is decided elsewhere. This analysis only looks at whether subterms 609 ** appropriate for indexing exist. 610 ** 611 ** All examples A through E above satisfy case 3. But if a term 612 ** also satisfies case 1 (such as B) we know that the optimizer will 613 ** always prefer case 1, so in that case we pretend that case 3 is not 614 ** satisfied. 615 ** 616 ** It might be the case that multiple tables are indexable. For example, 617 ** (E) above is indexable on tables P, Q, and R. 618 ** 619 ** Terms that satisfy case 3 are candidates for lookup by using 620 ** separate indices to find rowids for each subterm and composing 621 ** the union of all rowids using a RowSet object. This is similar 622 ** to "bitmap indices" in other database engines. 623 ** 624 ** OTHERWISE: 625 ** 626 ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to 627 ** zero. This term is not useful for search. 628 */ 629 static void exprAnalyzeOrTerm( 630 SrcList *pSrc, /* the FROM clause */ 631 WhereClause *pWC, /* the complete WHERE clause */ 632 int idxTerm /* Index of the OR-term to be analyzed */ 633 ){ 634 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ 635 Parse *pParse = pWInfo->pParse; /* Parser context */ 636 sqlite3 *db = pParse->db; /* Database connection */ 637 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ 638 Expr *pExpr = pTerm->pExpr; /* The expression of the term */ 639 int i; /* Loop counters */ 640 WhereClause *pOrWc; /* Breakup of pTerm into subterms */ 641 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ 642 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ 643 Bitmask chngToIN; /* Tables that might satisfy case 1 */ 644 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ 645 646 /* 647 ** Break the OR clause into its separate subterms. The subterms are 648 ** stored in a WhereClause structure containing within the WhereOrInfo 649 ** object that is attached to the original OR clause term. 650 */ 651 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); 652 assert( pExpr->op==TK_OR ); 653 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); 654 if( pOrInfo==0 ) return; 655 pTerm->wtFlags |= TERM_ORINFO; 656 pOrWc = &pOrInfo->wc; 657 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic)); 658 sqlite3WhereClauseInit(pOrWc, pWInfo); 659 sqlite3WhereSplit(pOrWc, pExpr, TK_OR); 660 sqlite3WhereExprAnalyze(pSrc, pOrWc); 661 if( db->mallocFailed ) return; 662 assert( pOrWc->nTerm>=2 ); 663 664 /* 665 ** Compute the set of tables that might satisfy cases 1 or 3. 666 */ 667 indexable = ~(Bitmask)0; 668 chngToIN = ~(Bitmask)0; 669 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ 670 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ 671 WhereAndInfo *pAndInfo; 672 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); 673 chngToIN = 0; 674 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo)); 675 if( pAndInfo ){ 676 WhereClause *pAndWC; 677 WhereTerm *pAndTerm; 678 int j; 679 Bitmask b = 0; 680 pOrTerm->u.pAndInfo = pAndInfo; 681 pOrTerm->wtFlags |= TERM_ANDINFO; 682 pOrTerm->eOperator = WO_AND; 683 pAndWC = &pAndInfo->wc; 684 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic)); 685 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo); 686 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND); 687 sqlite3WhereExprAnalyze(pSrc, pAndWC); 688 pAndWC->pOuter = pWC; 689 if( !db->mallocFailed ){ 690 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){ 691 assert( pAndTerm->pExpr ); 692 if( allowedOp(pAndTerm->pExpr->op) 693 || pAndTerm->eOperator==WO_AUX 694 ){ 695 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); 696 } 697 } 698 } 699 indexable &= b; 700 } 701 }else if( pOrTerm->wtFlags & TERM_COPIED ){ 702 /* Skip this term for now. We revisit it when we process the 703 ** corresponding TERM_VIRTUAL term */ 704 }else{ 705 Bitmask b; 706 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); 707 if( pOrTerm->wtFlags & TERM_VIRTUAL ){ 708 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; 709 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor); 710 } 711 indexable &= b; 712 if( (pOrTerm->eOperator & WO_EQ)==0 ){ 713 chngToIN = 0; 714 }else{ 715 chngToIN &= b; 716 } 717 } 718 } 719 720 /* 721 ** Record the set of tables that satisfy case 3. The set might be 722 ** empty. 723 */ 724 pOrInfo->indexable = indexable; 725 if( indexable ){ 726 pTerm->eOperator = WO_OR; 727 pWC->hasOr = 1; 728 }else{ 729 pTerm->eOperator = WO_OR; 730 } 731 732 /* For a two-way OR, attempt to implementation case 2. 733 */ 734 if( indexable && pOrWc->nTerm==2 ){ 735 int iOne = 0; 736 WhereTerm *pOne; 737 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){ 738 int iTwo = 0; 739 WhereTerm *pTwo; 740 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){ 741 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo); 742 } 743 } 744 } 745 746 /* 747 ** chngToIN holds a set of tables that *might* satisfy case 1. But 748 ** we have to do some additional checking to see if case 1 really 749 ** is satisfied. 750 ** 751 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means 752 ** that there is no possibility of transforming the OR clause into an 753 ** IN operator because one or more terms in the OR clause contain 754 ** something other than == on a column in the single table. The 1-bit 755 ** case means that every term of the OR clause is of the form 756 ** "table.column=expr" for some single table. The one bit that is set 757 ** will correspond to the common table. We still need to check to make 758 ** sure the same column is used on all terms. The 2-bit case is when 759 ** the all terms are of the form "table1.column=table2.column". It 760 ** might be possible to form an IN operator with either table1.column 761 ** or table2.column as the LHS if either is common to every term of 762 ** the OR clause. 763 ** 764 ** Note that terms of the form "table.column1=table.column2" (the 765 ** same table on both sizes of the ==) cannot be optimized. 766 */ 767 if( chngToIN ){ 768 int okToChngToIN = 0; /* True if the conversion to IN is valid */ 769 int iColumn = -1; /* Column index on lhs of IN operator */ 770 int iCursor = -1; /* Table cursor common to all terms */ 771 int j = 0; /* Loop counter */ 772 773 /* Search for a table and column that appears on one side or the 774 ** other of the == operator in every subterm. That table and column 775 ** will be recorded in iCursor and iColumn. There might not be any 776 ** such table and column. Set okToChngToIN if an appropriate table 777 ** and column is found but leave okToChngToIN false if not found. 778 */ 779 for(j=0; j<2 && !okToChngToIN; j++){ 780 Expr *pLeft = 0; 781 pOrTerm = pOrWc->a; 782 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ 783 assert( pOrTerm->eOperator & WO_EQ ); 784 pOrTerm->wtFlags &= ~TERM_OR_OK; 785 if( pOrTerm->leftCursor==iCursor ){ 786 /* This is the 2-bit case and we are on the second iteration and 787 ** current term is from the first iteration. So skip this term. */ 788 assert( j==1 ); 789 continue; 790 } 791 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet, 792 pOrTerm->leftCursor))==0 ){ 793 /* This term must be of the form t1.a==t2.b where t2 is in the 794 ** chngToIN set but t1 is not. This term will be either preceded 795 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term 796 ** and use its inversion. */ 797 testcase( pOrTerm->wtFlags & TERM_COPIED ); 798 testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); 799 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); 800 continue; 801 } 802 iColumn = pOrTerm->u.x.leftColumn; 803 iCursor = pOrTerm->leftCursor; 804 pLeft = pOrTerm->pExpr->pLeft; 805 break; 806 } 807 if( i<0 ){ 808 /* No candidate table+column was found. This can only occur 809 ** on the second iteration */ 810 assert( j==1 ); 811 assert( IsPowerOfTwo(chngToIN) ); 812 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) ); 813 break; 814 } 815 testcase( j==1 ); 816 817 /* We have found a candidate table and column. Check to see if that 818 ** table and column is common to every term in the OR clause */ 819 okToChngToIN = 1; 820 for(; i>=0 && okToChngToIN; i--, pOrTerm++){ 821 assert( pOrTerm->eOperator & WO_EQ ); 822 if( pOrTerm->leftCursor!=iCursor ){ 823 pOrTerm->wtFlags &= ~TERM_OR_OK; 824 }else if( pOrTerm->u.x.leftColumn!=iColumn || (iColumn==XN_EXPR 825 && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1) 826 )){ 827 okToChngToIN = 0; 828 }else{ 829 int affLeft, affRight; 830 /* If the right-hand side is also a column, then the affinities 831 ** of both right and left sides must be such that no type 832 ** conversions are required on the right. (Ticket #2249) 833 */ 834 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); 835 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); 836 if( affRight!=0 && affRight!=affLeft ){ 837 okToChngToIN = 0; 838 }else{ 839 pOrTerm->wtFlags |= TERM_OR_OK; 840 } 841 } 842 } 843 } 844 845 /* At this point, okToChngToIN is true if original pTerm satisfies 846 ** case 1. In that case, construct a new virtual term that is 847 ** pTerm converted into an IN operator. 848 */ 849 if( okToChngToIN ){ 850 Expr *pDup; /* A transient duplicate expression */ 851 ExprList *pList = 0; /* The RHS of the IN operator */ 852 Expr *pLeft = 0; /* The LHS of the IN operator */ 853 Expr *pNew; /* The complete IN operator */ 854 855 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ 856 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; 857 assert( pOrTerm->eOperator & WO_EQ ); 858 assert( pOrTerm->leftCursor==iCursor ); 859 assert( pOrTerm->u.x.leftColumn==iColumn ); 860 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); 861 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); 862 pLeft = pOrTerm->pExpr->pLeft; 863 } 864 assert( pLeft!=0 ); 865 pDup = sqlite3ExprDup(db, pLeft, 0); 866 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0); 867 if( pNew ){ 868 int idxNew; 869 transferJoinMarkings(pNew, pExpr); 870 assert( !ExprHasProperty(pNew, EP_xIsSelect) ); 871 pNew->x.pList = pList; 872 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); 873 testcase( idxNew==0 ); 874 exprAnalyze(pSrc, pWC, idxNew); 875 /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */ 876 markTermAsChild(pWC, idxNew, idxTerm); 877 }else{ 878 sqlite3ExprListDelete(db, pList); 879 } 880 } 881 } 882 } 883 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ 884 885 /* 886 ** We already know that pExpr is a binary operator where both operands are 887 ** column references. This routine checks to see if pExpr is an equivalence 888 ** relation: 889 ** 1. The SQLITE_Transitive optimization must be enabled 890 ** 2. Must be either an == or an IS operator 891 ** 3. Not originating in the ON clause of an OUTER JOIN 892 ** 4. The affinities of A and B must be compatible 893 ** 5a. Both operands use the same collating sequence OR 894 ** 5b. The overall collating sequence is BINARY 895 ** If this routine returns TRUE, that means that the RHS can be substituted 896 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs. 897 ** This is an optimization. No harm comes from returning 0. But if 1 is 898 ** returned when it should not be, then incorrect answers might result. 899 */ 900 static int termIsEquivalence(Parse *pParse, Expr *pExpr){ 901 char aff1, aff2; 902 CollSeq *pColl; 903 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0; 904 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0; 905 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0; 906 aff1 = sqlite3ExprAffinity(pExpr->pLeft); 907 aff2 = sqlite3ExprAffinity(pExpr->pRight); 908 if( aff1!=aff2 909 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2)) 910 ){ 911 return 0; 912 } 913 pColl = sqlite3ExprCompareCollSeq(pParse, pExpr); 914 if( sqlite3IsBinary(pColl) ) return 1; 915 return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight); 916 } 917 918 /* 919 ** Recursively walk the expressions of a SELECT statement and generate 920 ** a bitmask indicating which tables are used in that expression 921 ** tree. 922 */ 923 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){ 924 Bitmask mask = 0; 925 while( pS ){ 926 SrcList *pSrc = pS->pSrc; 927 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList); 928 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy); 929 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy); 930 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere); 931 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving); 932 if( ALWAYS(pSrc!=0) ){ 933 int i; 934 for(i=0; i<pSrc->nSrc; i++){ 935 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect); 936 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn); 937 if( pSrc->a[i].fg.isTabFunc ){ 938 mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg); 939 } 940 } 941 } 942 pS = pS->pPrior; 943 } 944 return mask; 945 } 946 947 /* 948 ** Expression pExpr is one operand of a comparison operator that might 949 ** be useful for indexing. This routine checks to see if pExpr appears 950 ** in any index. Return TRUE (1) if pExpr is an indexed term and return 951 ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor 952 ** number of the table that is indexed and aiCurCol[1] to the column number 953 ** of the column that is indexed, or XN_EXPR (-2) if an expression is being 954 ** indexed. 955 ** 956 ** If pExpr is a TK_COLUMN column reference, then this routine always returns 957 ** true even if that particular column is not indexed, because the column 958 ** might be added to an automatic index later. 959 */ 960 static SQLITE_NOINLINE int exprMightBeIndexed2( 961 SrcList *pFrom, /* The FROM clause */ 962 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ 963 int *aiCurCol, /* Write the referenced table cursor and column here */ 964 Expr *pExpr /* An operand of a comparison operator */ 965 ){ 966 Index *pIdx; 967 int i; 968 int iCur; 969 for(i=0; mPrereq>1; i++, mPrereq>>=1){} 970 iCur = pFrom->a[i].iCursor; 971 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){ 972 if( pIdx->aColExpr==0 ) continue; 973 for(i=0; i<pIdx->nKeyCol; i++){ 974 if( pIdx->aiColumn[i]!=XN_EXPR ) continue; 975 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){ 976 aiCurCol[0] = iCur; 977 aiCurCol[1] = XN_EXPR; 978 return 1; 979 } 980 } 981 } 982 return 0; 983 } 984 static int exprMightBeIndexed( 985 SrcList *pFrom, /* The FROM clause */ 986 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */ 987 int *aiCurCol, /* Write the referenced table cursor & column here */ 988 Expr *pExpr, /* An operand of a comparison operator */ 989 int op /* The specific comparison operator */ 990 ){ 991 /* If this expression is a vector to the left or right of a 992 ** inequality constraint (>, <, >= or <=), perform the processing 993 ** on the first element of the vector. */ 994 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE ); 995 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE ); 996 assert( op<=TK_GE ); 997 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){ 998 pExpr = pExpr->x.pList->a[0].pExpr; 999 } 1000 1001 if( pExpr->op==TK_COLUMN ){ 1002 aiCurCol[0] = pExpr->iTable; 1003 aiCurCol[1] = pExpr->iColumn; 1004 return 1; 1005 } 1006 if( mPrereq==0 ) return 0; /* No table references */ 1007 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */ 1008 return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr); 1009 } 1010 1011 /* 1012 ** Expression callback for exprUsesSrclist(). 1013 */ 1014 static int exprUsesSrclistCb(Walker *p, Expr *pExpr){ 1015 if( pExpr->op==TK_COLUMN ){ 1016 SrcList *pSrc = p->u.pSrcList; 1017 int iCsr = pExpr->iTable; 1018 int ii; 1019 for(ii=0; ii<pSrc->nSrc; ii++){ 1020 if( pSrc->a[ii].iCursor==iCsr ){ 1021 return p->eCode ? WRC_Abort : WRC_Continue; 1022 } 1023 } 1024 return p->eCode ? WRC_Continue : WRC_Abort; 1025 } 1026 return WRC_Continue; 1027 } 1028 1029 /* 1030 ** Select callback for exprUsesSrclist(). 1031 */ 1032 static int exprUsesSrclistSelectCb(Walker *NotUsed1, Select *NotUsed2){ 1033 UNUSED_PARAMETER(NotUsed1); 1034 UNUSED_PARAMETER(NotUsed2); 1035 return WRC_Abort; 1036 } 1037 1038 /* 1039 ** This function always returns true if expression pExpr contains 1040 ** a sub-select. 1041 ** 1042 ** If there is no sub-select in pExpr, then return true if pExpr 1043 ** contains a TK_COLUMN node for a table that is (bUses==1) 1044 ** or is not (bUses==0) in pSrc. 1045 ** 1046 ** Said another way: 1047 ** 1048 ** bUses Return Meaning 1049 ** -------- ------ ------------------------------------------------ 1050 ** 1051 ** bUses==1 true pExpr contains either a sub-select or a 1052 ** TK_COLUMN referencing pSrc. 1053 ** 1054 ** bUses==1 false pExpr contains no sub-selects and all TK_COLUMN 1055 ** nodes reference tables not found in pSrc 1056 ** 1057 ** bUses==0 true pExpr contains either a sub-select or a TK_COLUMN 1058 ** that references a table not in pSrc. 1059 ** 1060 ** bUses==0 false pExpr contains no sub-selects and all TK_COLUMN 1061 ** nodes reference pSrc 1062 */ 1063 static int exprUsesSrclist(SrcList *pSrc, Expr *pExpr, int bUses){ 1064 Walker sWalker; 1065 memset(&sWalker, 0, sizeof(Walker)); 1066 sWalker.eCode = bUses; 1067 sWalker.u.pSrcList = pSrc; 1068 sWalker.xExprCallback = exprUsesSrclistCb; 1069 sWalker.xSelectCallback = exprUsesSrclistSelectCb; 1070 return (sqlite3WalkExpr(&sWalker, pExpr)==WRC_Abort); 1071 } 1072 1073 /* 1074 ** Context object used by exprExistsToInIter() as it iterates through an 1075 ** expression tree. 1076 */ 1077 struct ExistsToInCtx { 1078 SrcList *pSrc; /* The tables in an EXISTS(SELECT ... FROM <here> ...) */ 1079 Expr *pInLhs; /* OUT: Use this as the LHS of the IN operator */ 1080 Expr *pEq; /* OUT: The == term that include pInLhs */ 1081 Expr **ppAnd; /* OUT: The AND operator that includes pEq as a child */ 1082 Expr **ppParent; /* The AND operator currently being examined */ 1083 }; 1084 1085 /* 1086 ** Iterate through all AND connected nodes in the expression tree 1087 ** headed by (*ppExpr), populating the structure passed as the first 1088 ** argument with the values required by exprAnalyzeExistsFindEq(). 1089 ** 1090 ** This function returns non-zero if the expression tree does not meet 1091 ** the two conditions described by the header comment for 1092 ** exprAnalyzeExistsFindEq(), or zero if it does. 1093 */ 1094 static int exprExistsToInIter(struct ExistsToInCtx *p, Expr **ppExpr){ 1095 Expr *pExpr = *ppExpr; 1096 switch( pExpr->op ){ 1097 case TK_AND: 1098 p->ppParent = ppExpr; 1099 if( exprExistsToInIter(p, &pExpr->pLeft) ) return 1; 1100 p->ppParent = ppExpr; 1101 if( exprExistsToInIter(p, &pExpr->pRight) ) return 1; 1102 break; 1103 case TK_EQ: { 1104 int bLeft = exprUsesSrclist(p->pSrc, pExpr->pLeft, 0); 1105 int bRight = exprUsesSrclist(p->pSrc, pExpr->pRight, 0); 1106 if( bLeft || bRight ){ 1107 if( (bLeft && bRight) || p->pInLhs ) return 1; 1108 p->pInLhs = bLeft ? pExpr->pLeft : pExpr->pRight; 1109 if( exprUsesSrclist(p->pSrc, p->pInLhs, 1) ) return 1; 1110 p->pEq = pExpr; 1111 p->ppAnd = p->ppParent; 1112 } 1113 break; 1114 } 1115 default: 1116 if( exprUsesSrclist(p->pSrc, pExpr, 0) ){ 1117 return 1; 1118 } 1119 break; 1120 } 1121 1122 return 0; 1123 } 1124 1125 /* 1126 ** This function is used by exprAnalyzeExists() when creating virtual IN(...) 1127 ** terms equivalent to user-supplied EXIST(...) clauses. It splits the WHERE 1128 ** clause of the Select object passed as the first argument into one or more 1129 ** expressions joined by AND operators, and then tests if the following are 1130 ** true: 1131 ** 1132 ** 1. Exactly one of the AND separated terms refers to the outer 1133 ** query, and it is an == (TK_EQ) expression. 1134 ** 1135 ** 2. Only one side of the == expression refers to the outer query, and 1136 ** it does not refer to any columns from the inner query. 1137 ** 1138 ** If both these conditions are true, then a pointer to the side of the == 1139 ** expression that refers to the outer query is returned. The caller will 1140 ** use this expression as the LHS of the IN(...) virtual term. Or, if one 1141 ** or both of the above conditions are not true, NULL is returned. 1142 ** 1143 ** If non-NULL is returned and ppEq is non-NULL, *ppEq is set to point 1144 ** to the == expression node before returning. If pppAnd is non-NULL and 1145 ** the == node is not the root of the WHERE clause, then *pppAnd is set 1146 ** to point to the pointer to the AND node that is the parent of the == 1147 ** node within the WHERE expression tree. 1148 */ 1149 static Expr *exprAnalyzeExistsFindEq( 1150 Select *pSel, /* The SELECT of the EXISTS */ 1151 Expr **ppEq, /* OUT: == node from WHERE clause */ 1152 Expr ***pppAnd /* OUT: Pointer to parent of ==, if any */ 1153 ){ 1154 struct ExistsToInCtx ctx; 1155 memset(&ctx, 0, sizeof(ctx)); 1156 ctx.pSrc = pSel->pSrc; 1157 if( exprExistsToInIter(&ctx, &pSel->pWhere) ){ 1158 return 0; 1159 } 1160 if( ppEq ) *ppEq = ctx.pEq; 1161 if( pppAnd ) *pppAnd = ctx.ppAnd; 1162 return ctx.pInLhs; 1163 } 1164 1165 /* 1166 ** Term idxTerm of the WHERE clause passed as the second argument is an 1167 ** EXISTS expression with a correlated SELECT statement on the RHS. 1168 ** This function analyzes the SELECT statement, and if possible adds an 1169 ** equivalent "? IN(SELECT...)" virtual term to the WHERE clause. 1170 ** 1171 ** For an EXISTS term such as the following: 1172 ** 1173 ** EXISTS (SELECT ... FROM <srclist> WHERE <e1> = <e2> AND <e3>) 1174 ** 1175 ** The virtual IN() term added is: 1176 ** 1177 ** <e1> IN (SELECT <e2> FROM <srclist> WHERE <e3>) 1178 ** 1179 ** The virtual term is only added if the following conditions are met: 1180 ** 1181 ** 1. The sub-select must not be an aggregate or use window functions, 1182 ** 1183 ** 2. The sub-select must not be a compound SELECT, 1184 ** 1185 ** 3. Expression <e1> must refer to at least one column from the outer 1186 ** query, and must not refer to any column from the inner query 1187 ** (i.e. from <srclist>). 1188 ** 1189 ** 4. <e2> and <e3> must not refer to any values from the outer query. 1190 ** In other words, once <e1> has been removed, the inner query 1191 ** must not be correlated. 1192 ** 1193 */ 1194 static void exprAnalyzeExists( 1195 SrcList *pSrc, /* the FROM clause */ 1196 WhereClause *pWC, /* the WHERE clause */ 1197 int idxTerm /* Index of the term to be analyzed */ 1198 ){ 1199 Parse *pParse = pWC->pWInfo->pParse; 1200 WhereTerm *pTerm = &pWC->a[idxTerm]; 1201 Expr *pExpr = pTerm->pExpr; 1202 Select *pSel = pExpr->x.pSelect; 1203 Expr *pDup = 0; 1204 Expr *pEq = 0; 1205 Expr *pRet = 0; 1206 Expr *pInLhs = 0; 1207 Expr **ppAnd = 0; 1208 int idxNew; 1209 sqlite3 *db = pParse->db; 1210 1211 assert( pExpr->op==TK_EXISTS ); 1212 assert( (pExpr->flags & EP_VarSelect) && (pExpr->flags & EP_xIsSelect) ); 1213 1214 if( pSel->selFlags & SF_Aggregate ) return; 1215 #ifndef SQLITE_OMIT_WINDOWFUNC 1216 if( pSel->pWin ) return; 1217 #endif 1218 if( pSel->pPrior ) return; 1219 if( pSel->pWhere==0 ) return; 1220 if( pSel->pLimit ) return; 1221 if( 0==exprAnalyzeExistsFindEq(pSel, 0, 0) ) return; 1222 1223 pDup = sqlite3ExprDup(db, pExpr, 0); 1224 if( db->mallocFailed ){ 1225 sqlite3ExprDelete(db, pDup); 1226 return; 1227 } 1228 pSel = pDup->x.pSelect; 1229 sqlite3ExprListDelete(db, pSel->pEList); 1230 pSel->pEList = 0; 1231 1232 pInLhs = exprAnalyzeExistsFindEq(pSel, &pEq, &ppAnd); 1233 assert( pInLhs && pEq ); 1234 assert( pEq==pSel->pWhere || ppAnd ); 1235 if( pInLhs==pEq->pLeft ){ 1236 pRet = pEq->pRight; 1237 }else{ 1238 CollSeq *p = sqlite3ExprCompareCollSeq(pParse, pEq); 1239 pInLhs = sqlite3ExprAddCollateString(pParse, pInLhs, p?p->zName:"BINARY"); 1240 pRet = pEq->pLeft; 1241 } 1242 1243 assert( pDup->pLeft==0 ); 1244 pDup->op = TK_IN; 1245 pDup->pLeft = pInLhs; 1246 pDup->flags &= ~EP_VarSelect; 1247 if( pRet->op==TK_VECTOR ){ 1248 pSel->pEList = pRet->x.pList; 1249 pRet->x.pList = 0; 1250 sqlite3ExprDelete(db, pRet); 1251 }else{ 1252 pSel->pEList = sqlite3ExprListAppend(pParse, 0, pRet); 1253 } 1254 pEq->pLeft = 0; 1255 pEq->pRight = 0; 1256 if( ppAnd ){ 1257 Expr *pAnd = *ppAnd; 1258 Expr *pOther = (pAnd->pLeft==pEq) ? pAnd->pRight : pAnd->pLeft; 1259 pAnd->pLeft = pAnd->pRight = 0; 1260 sqlite3ExprDelete(db, pAnd); 1261 *ppAnd = pOther; 1262 }else{ 1263 assert( pSel->pWhere==pEq ); 1264 pSel->pWhere = 0; 1265 } 1266 sqlite3ExprDelete(db, pEq); 1267 1268 #ifdef WHERETRACE_ENABLED /* 0x20 */ 1269 if( sqlite3WhereTrace & 0x20 ){ 1270 sqlite3DebugPrintf("Convert EXISTS:\n"); 1271 sqlite3TreeViewExpr(0, pExpr, 0); 1272 sqlite3DebugPrintf("into IN:\n"); 1273 sqlite3TreeViewExpr(0, pDup, 0); 1274 } 1275 #endif 1276 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); 1277 exprAnalyze(pSrc, pWC, idxNew); 1278 markTermAsChild(pWC, idxNew, idxTerm); 1279 pWC->a[idxTerm].wtFlags |= TERM_COPIED; 1280 } 1281 1282 /* 1283 ** The input to this routine is an WhereTerm structure with only the 1284 ** "pExpr" field filled in. The job of this routine is to analyze the 1285 ** subexpression and populate all the other fields of the WhereTerm 1286 ** structure. 1287 ** 1288 ** If the expression is of the form "<expr> <op> X" it gets commuted 1289 ** to the standard form of "X <op> <expr>". 1290 ** 1291 ** If the expression is of the form "X <op> Y" where both X and Y are 1292 ** columns, then the original expression is unchanged and a new virtual 1293 ** term of the form "Y <op> X" is added to the WHERE clause and 1294 ** analyzed separately. The original term is marked with TERM_COPIED 1295 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr 1296 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it 1297 ** is a commuted copy of a prior term.) The original term has nChild=1 1298 ** and the copy has idxParent set to the index of the original term. 1299 */ 1300 static void exprAnalyze( 1301 SrcList *pSrc, /* the FROM clause */ 1302 WhereClause *pWC, /* the WHERE clause */ 1303 int idxTerm /* Index of the term to be analyzed */ 1304 ){ 1305 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ 1306 WhereTerm *pTerm; /* The term to be analyzed */ 1307 WhereMaskSet *pMaskSet; /* Set of table index masks */ 1308 Expr *pExpr; /* The expression to be analyzed */ 1309 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ 1310 Bitmask prereqAll; /* Prerequesites of pExpr */ 1311 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ 1312 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ 1313 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ 1314 int noCase = 0; /* uppercase equivalent to lowercase */ 1315 int op; /* Top-level operator. pExpr->op */ 1316 Parse *pParse = pWInfo->pParse; /* Parsing context */ 1317 sqlite3 *db = pParse->db; /* Database connection */ 1318 unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */ 1319 int nLeft; /* Number of elements on left side vector */ 1320 1321 if( db->mallocFailed ){ 1322 return; 1323 } 1324 pTerm = &pWC->a[idxTerm]; 1325 pMaskSet = &pWInfo->sMaskSet; 1326 pExpr = pTerm->pExpr; 1327 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); 1328 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft); 1329 op = pExpr->op; 1330 if( op==TK_IN ){ 1331 assert( pExpr->pRight==0 ); 1332 if( sqlite3ExprCheckIN(pParse, pExpr) ) return; 1333 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ 1334 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect); 1335 }else{ 1336 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList); 1337 } 1338 }else if( op==TK_ISNULL ){ 1339 pTerm->prereqRight = 0; 1340 }else{ 1341 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight); 1342 } 1343 pMaskSet->bVarSelect = 0; 1344 prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr); 1345 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT; 1346 if( ExprHasProperty(pExpr, EP_FromJoin) ){ 1347 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable); 1348 prereqAll |= x; 1349 extraRight = x-1; /* ON clause terms may not be used with an index 1350 ** on left table of a LEFT JOIN. Ticket #3015 */ 1351 if( (prereqAll>>1)>=x ){ 1352 sqlite3ErrorMsg(pParse, "ON clause references tables to its right"); 1353 return; 1354 } 1355 } 1356 pTerm->prereqAll = prereqAll; 1357 pTerm->leftCursor = -1; 1358 pTerm->iParent = -1; 1359 pTerm->eOperator = 0; 1360 if( allowedOp(op) ){ 1361 int aiCurCol[2]; 1362 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); 1363 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); 1364 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; 1365 1366 if( pTerm->u.x.iField>0 ){ 1367 assert( op==TK_IN ); 1368 assert( pLeft->op==TK_VECTOR ); 1369 pLeft = pLeft->x.pList->a[pTerm->u.x.iField-1].pExpr; 1370 } 1371 1372 if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){ 1373 pTerm->leftCursor = aiCurCol[0]; 1374 pTerm->u.x.leftColumn = aiCurCol[1]; 1375 pTerm->eOperator = operatorMask(op) & opMask; 1376 } 1377 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS; 1378 if( pRight 1379 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op) 1380 ){ 1381 WhereTerm *pNew; 1382 Expr *pDup; 1383 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ 1384 assert( pTerm->u.x.iField==0 ); 1385 if( pTerm->leftCursor>=0 ){ 1386 int idxNew; 1387 pDup = sqlite3ExprDup(db, pExpr, 0); 1388 if( db->mallocFailed ){ 1389 sqlite3ExprDelete(db, pDup); 1390 return; 1391 } 1392 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); 1393 if( idxNew==0 ) return; 1394 pNew = &pWC->a[idxNew]; 1395 markTermAsChild(pWC, idxNew, idxTerm); 1396 if( op==TK_IS ) pNew->wtFlags |= TERM_IS; 1397 pTerm = &pWC->a[idxTerm]; 1398 pTerm->wtFlags |= TERM_COPIED; 1399 1400 if( termIsEquivalence(pParse, pDup) ){ 1401 pTerm->eOperator |= WO_EQUIV; 1402 eExtraOp = WO_EQUIV; 1403 } 1404 }else{ 1405 pDup = pExpr; 1406 pNew = pTerm; 1407 } 1408 pNew->wtFlags |= exprCommute(pParse, pDup); 1409 pNew->leftCursor = aiCurCol[0]; 1410 pNew->u.x.leftColumn = aiCurCol[1]; 1411 testcase( (prereqLeft | extraRight) != prereqLeft ); 1412 pNew->prereqRight = prereqLeft | extraRight; 1413 pNew->prereqAll = prereqAll; 1414 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask; 1415 }else if( op==TK_ISNULL && 0==sqlite3ExprCanBeNull(pLeft) ){ 1416 pExpr->op = TK_TRUEFALSE; 1417 pExpr->u.zToken = "false"; 1418 ExprSetProperty(pExpr, EP_IsFalse); 1419 pTerm->prereqAll = 0; 1420 pTerm->eOperator = 0; 1421 } 1422 } 1423 1424 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION 1425 /* If a term is the BETWEEN operator, create two new virtual terms 1426 ** that define the range that the BETWEEN implements. For example: 1427 ** 1428 ** a BETWEEN b AND c 1429 ** 1430 ** is converted into: 1431 ** 1432 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) 1433 ** 1434 ** The two new terms are added onto the end of the WhereClause object. 1435 ** The new terms are "dynamic" and are children of the original BETWEEN 1436 ** term. That means that if the BETWEEN term is coded, the children are 1437 ** skipped. Or, if the children are satisfied by an index, the original 1438 ** BETWEEN term is skipped. 1439 */ 1440 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ 1441 ExprList *pList = pExpr->x.pList; 1442 int i; 1443 static const u8 ops[] = {TK_GE, TK_LE}; 1444 assert( pList!=0 ); 1445 assert( pList->nExpr==2 ); 1446 for(i=0; i<2; i++){ 1447 Expr *pNewExpr; 1448 int idxNew; 1449 pNewExpr = sqlite3PExpr(pParse, ops[i], 1450 sqlite3ExprDup(db, pExpr->pLeft, 0), 1451 sqlite3ExprDup(db, pList->a[i].pExpr, 0)); 1452 transferJoinMarkings(pNewExpr, pExpr); 1453 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); 1454 testcase( idxNew==0 ); 1455 exprAnalyze(pSrc, pWC, idxNew); 1456 pTerm = &pWC->a[idxTerm]; 1457 markTermAsChild(pWC, idxNew, idxTerm); 1458 } 1459 } 1460 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ 1461 1462 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) 1463 /* Analyze a term that is composed of two or more subterms connected by 1464 ** an OR operator. 1465 */ 1466 else if( pExpr->op==TK_OR ){ 1467 assert( pWC->op==TK_AND ); 1468 exprAnalyzeOrTerm(pSrc, pWC, idxTerm); 1469 pTerm = &pWC->a[idxTerm]; 1470 } 1471 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ 1472 1473 else if( pExpr->op==TK_EXISTS ){ 1474 /* Perhaps treat an EXISTS operator as an IN operator */ 1475 if( (pExpr->flags & EP_VarSelect)!=0 1476 && OptimizationEnabled(db, SQLITE_ExistsToIN) 1477 ){ 1478 exprAnalyzeExists(pSrc, pWC, idxTerm); 1479 } 1480 } 1481 1482 /* The form "x IS NOT NULL" can sometimes be evaluated more efficiently 1483 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a 1484 ** virtual term of that form. 1485 ** 1486 ** The virtual term must be tagged with TERM_VNULL. 1487 */ 1488 else if( pExpr->op==TK_NOTNULL ){ 1489 if( pExpr->pLeft->op==TK_COLUMN 1490 && pExpr->pLeft->iColumn>=0 1491 && !ExprHasProperty(pExpr, EP_FromJoin) 1492 ){ 1493 Expr *pNewExpr; 1494 Expr *pLeft = pExpr->pLeft; 1495 int idxNew; 1496 WhereTerm *pNewTerm; 1497 1498 pNewExpr = sqlite3PExpr(pParse, TK_GT, 1499 sqlite3ExprDup(db, pLeft, 0), 1500 sqlite3ExprAlloc(db, TK_NULL, 0, 0)); 1501 1502 idxNew = whereClauseInsert(pWC, pNewExpr, 1503 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); 1504 if( idxNew ){ 1505 pNewTerm = &pWC->a[idxNew]; 1506 pNewTerm->prereqRight = 0; 1507 pNewTerm->leftCursor = pLeft->iTable; 1508 pNewTerm->u.x.leftColumn = pLeft->iColumn; 1509 pNewTerm->eOperator = WO_GT; 1510 markTermAsChild(pWC, idxNew, idxTerm); 1511 pTerm = &pWC->a[idxTerm]; 1512 pTerm->wtFlags |= TERM_COPIED; 1513 pNewTerm->prereqAll = pTerm->prereqAll; 1514 } 1515 } 1516 } 1517 1518 1519 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION 1520 /* Add constraints to reduce the search space on a LIKE or GLOB 1521 ** operator. 1522 ** 1523 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints 1524 ** 1525 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%' 1526 ** 1527 ** The last character of the prefix "abc" is incremented to form the 1528 ** termination condition "abd". If case is not significant (the default 1529 ** for LIKE) then the lower-bound is made all uppercase and the upper- 1530 ** bound is made all lowercase so that the bounds also work when comparing 1531 ** BLOBs. 1532 */ 1533 else if( pExpr->op==TK_FUNCTION 1534 && pWC->op==TK_AND 1535 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) 1536 ){ 1537 Expr *pLeft; /* LHS of LIKE/GLOB operator */ 1538 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ 1539 Expr *pNewExpr1; 1540 Expr *pNewExpr2; 1541 int idxNew1; 1542 int idxNew2; 1543 const char *zCollSeqName; /* Name of collating sequence */ 1544 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC; 1545 1546 pLeft = pExpr->x.pList->a[1].pExpr; 1547 pStr2 = sqlite3ExprDup(db, pStr1, 0); 1548 1549 /* Convert the lower bound to upper-case and the upper bound to 1550 ** lower-case (upper-case is less than lower-case in ASCII) so that 1551 ** the range constraints also work for BLOBs 1552 */ 1553 if( noCase && !pParse->db->mallocFailed ){ 1554 int i; 1555 char c; 1556 pTerm->wtFlags |= TERM_LIKE; 1557 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){ 1558 pStr1->u.zToken[i] = sqlite3Toupper(c); 1559 pStr2->u.zToken[i] = sqlite3Tolower(c); 1560 } 1561 } 1562 1563 if( !db->mallocFailed ){ 1564 u8 c, *pC; /* Last character before the first wildcard */ 1565 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; 1566 c = *pC; 1567 if( noCase ){ 1568 /* The point is to increment the last character before the first 1569 ** wildcard. But if we increment '@', that will push it into the 1570 ** alphabetic range where case conversions will mess up the 1571 ** inequality. To avoid this, make sure to also run the full 1572 ** LIKE on all candidate expressions by clearing the isComplete flag 1573 */ 1574 if( c=='A'-1 ) isComplete = 0; 1575 c = sqlite3UpperToLower[c]; 1576 } 1577 *pC = c + 1; 1578 } 1579 zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY; 1580 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); 1581 pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 1582 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName), 1583 pStr1); 1584 transferJoinMarkings(pNewExpr1, pExpr); 1585 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags); 1586 testcase( idxNew1==0 ); 1587 exprAnalyze(pSrc, pWC, idxNew1); 1588 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); 1589 pNewExpr2 = sqlite3PExpr(pParse, TK_LT, 1590 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), 1591 pStr2); 1592 transferJoinMarkings(pNewExpr2, pExpr); 1593 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags); 1594 testcase( idxNew2==0 ); 1595 exprAnalyze(pSrc, pWC, idxNew2); 1596 pTerm = &pWC->a[idxTerm]; 1597 if( isComplete ){ 1598 markTermAsChild(pWC, idxNew1, idxTerm); 1599 markTermAsChild(pWC, idxNew2, idxTerm); 1600 } 1601 } 1602 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ 1603 1604 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create 1605 ** new terms for each component comparison - "a = ?" and "b = ?". The 1606 ** new terms completely replace the original vector comparison, which is 1607 ** no longer used. 1608 ** 1609 ** This is only required if at least one side of the comparison operation 1610 ** is not a sub-select. */ 1611 if( (pExpr->op==TK_EQ || pExpr->op==TK_IS) 1612 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1 1613 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft 1614 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0 1615 || (pExpr->pRight->flags & EP_xIsSelect)==0) 1616 && pWC->op==TK_AND 1617 ){ 1618 int i; 1619 for(i=0; i<nLeft; i++){ 1620 int idxNew; 1621 Expr *pNew; 1622 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i); 1623 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i); 1624 1625 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight); 1626 transferJoinMarkings(pNew, pExpr); 1627 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC); 1628 exprAnalyze(pSrc, pWC, idxNew); 1629 } 1630 pTerm = &pWC->a[idxTerm]; 1631 pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */ 1632 pTerm->eOperator = 0; 1633 } 1634 1635 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create 1636 ** a virtual term for each vector component. The expression object 1637 ** used by each such virtual term is pExpr (the full vector IN(...) 1638 ** expression). The WhereTerm.u.x.iField variable identifies the index within 1639 ** the vector on the LHS that the virtual term represents. 1640 ** 1641 ** This only works if the RHS is a simple SELECT (not a compound) that does 1642 ** not use window functions. 1643 */ 1644 else if( pExpr->op==TK_IN 1645 && pTerm->u.x.iField==0 1646 && pExpr->pLeft->op==TK_VECTOR 1647 && pExpr->x.pSelect->pPrior==0 1648 #ifndef SQLITE_OMIT_WINDOWFUNC 1649 && pExpr->x.pSelect->pWin==0 1650 #endif 1651 && pWC->op==TK_AND 1652 ){ 1653 int i; 1654 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){ 1655 int idxNew; 1656 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL); 1657 pWC->a[idxNew].u.x.iField = i+1; 1658 exprAnalyze(pSrc, pWC, idxNew); 1659 markTermAsChild(pWC, idxNew, idxTerm); 1660 } 1661 } 1662 1663 #ifndef SQLITE_OMIT_VIRTUALTABLE 1664 /* Add a WO_AUX auxiliary term to the constraint set if the 1665 ** current expression is of the form "column OP expr" where OP 1666 ** is an operator that gets passed into virtual tables but which is 1667 ** not normally optimized for ordinary tables. In other words, OP 1668 ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL. 1669 ** This information is used by the xBestIndex methods of 1670 ** virtual tables. The native query optimizer does not attempt 1671 ** to do anything with MATCH functions. 1672 */ 1673 else if( pWC->op==TK_AND ){ 1674 Expr *pRight = 0, *pLeft = 0; 1675 int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight); 1676 while( res-- > 0 ){ 1677 int idxNew; 1678 WhereTerm *pNewTerm; 1679 Bitmask prereqColumn, prereqExpr; 1680 1681 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight); 1682 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft); 1683 if( (prereqExpr & prereqColumn)==0 ){ 1684 Expr *pNewExpr; 1685 pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 1686 0, sqlite3ExprDup(db, pRight, 0)); 1687 if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){ 1688 ExprSetProperty(pNewExpr, EP_FromJoin); 1689 pNewExpr->iRightJoinTable = pExpr->iRightJoinTable; 1690 } 1691 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); 1692 testcase( idxNew==0 ); 1693 pNewTerm = &pWC->a[idxNew]; 1694 pNewTerm->prereqRight = prereqExpr; 1695 pNewTerm->leftCursor = pLeft->iTable; 1696 pNewTerm->u.x.leftColumn = pLeft->iColumn; 1697 pNewTerm->eOperator = WO_AUX; 1698 pNewTerm->eMatchOp = eOp2; 1699 markTermAsChild(pWC, idxNew, idxTerm); 1700 pTerm = &pWC->a[idxTerm]; 1701 pTerm->wtFlags |= TERM_COPIED; 1702 pNewTerm->prereqAll = pTerm->prereqAll; 1703 } 1704 SWAP(Expr*, pLeft, pRight); 1705 } 1706 } 1707 #endif /* SQLITE_OMIT_VIRTUALTABLE */ 1708 1709 /* Prevent ON clause terms of a LEFT JOIN from being used to drive 1710 ** an index for tables to the left of the join. 1711 */ 1712 testcase( pTerm!=&pWC->a[idxTerm] ); 1713 pTerm = &pWC->a[idxTerm]; 1714 pTerm->prereqRight |= extraRight; 1715 } 1716 1717 /*************************************************************************** 1718 ** Routines with file scope above. Interface to the rest of the where.c 1719 ** subsystem follows. 1720 ***************************************************************************/ 1721 1722 /* 1723 ** This routine identifies subexpressions in the WHERE clause where 1724 ** each subexpression is separated by the AND operator or some other 1725 ** operator specified in the op parameter. The WhereClause structure 1726 ** is filled with pointers to subexpressions. For example: 1727 ** 1728 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) 1729 ** \________/ \_______________/ \________________/ 1730 ** slot[0] slot[1] slot[2] 1731 ** 1732 ** The original WHERE clause in pExpr is unaltered. All this routine 1733 ** does is make slot[] entries point to substructure within pExpr. 1734 ** 1735 ** In the previous sentence and in the diagram, "slot[]" refers to 1736 ** the WhereClause.a[] array. The slot[] array grows as needed to contain 1737 ** all terms of the WHERE clause. 1738 */ 1739 void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ 1740 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr); 1741 pWC->op = op; 1742 assert( pE2!=0 || pExpr==0 ); 1743 if( pE2==0 ) return; 1744 if( pE2->op!=op ){ 1745 whereClauseInsert(pWC, pExpr, 0); 1746 }else{ 1747 sqlite3WhereSplit(pWC, pE2->pLeft, op); 1748 sqlite3WhereSplit(pWC, pE2->pRight, op); 1749 } 1750 } 1751 1752 /* 1753 ** Initialize a preallocated WhereClause structure. 1754 */ 1755 void sqlite3WhereClauseInit( 1756 WhereClause *pWC, /* The WhereClause to be initialized */ 1757 WhereInfo *pWInfo /* The WHERE processing context */ 1758 ){ 1759 pWC->pWInfo = pWInfo; 1760 pWC->hasOr = 0; 1761 pWC->pOuter = 0; 1762 pWC->nTerm = 0; 1763 pWC->nSlot = ArraySize(pWC->aStatic); 1764 pWC->a = pWC->aStatic; 1765 } 1766 1767 /* 1768 ** Deallocate a WhereClause structure. The WhereClause structure 1769 ** itself is not freed. This routine is the inverse of 1770 ** sqlite3WhereClauseInit(). 1771 */ 1772 void sqlite3WhereClauseClear(WhereClause *pWC){ 1773 int i; 1774 WhereTerm *a; 1775 sqlite3 *db = pWC->pWInfo->pParse->db; 1776 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ 1777 if( a->wtFlags & TERM_DYNAMIC ){ 1778 sqlite3ExprDelete(db, a->pExpr); 1779 } 1780 if( a->wtFlags & TERM_ORINFO ){ 1781 whereOrInfoDelete(db, a->u.pOrInfo); 1782 }else if( a->wtFlags & TERM_ANDINFO ){ 1783 whereAndInfoDelete(db, a->u.pAndInfo); 1784 } 1785 } 1786 if( pWC->a!=pWC->aStatic ){ 1787 sqlite3DbFree(db, pWC->a); 1788 } 1789 } 1790 1791 1792 /* 1793 ** These routines walk (recursively) an expression tree and generate 1794 ** a bitmask indicating which tables are used in that expression 1795 ** tree. 1796 */ 1797 Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){ 1798 Bitmask mask; 1799 if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){ 1800 return sqlite3WhereGetMask(pMaskSet, p->iTable); 1801 }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){ 1802 assert( p->op!=TK_IF_NULL_ROW ); 1803 return 0; 1804 } 1805 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0; 1806 if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft); 1807 if( p->pRight ){ 1808 mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight); 1809 assert( p->x.pList==0 ); 1810 }else if( ExprHasProperty(p, EP_xIsSelect) ){ 1811 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1; 1812 mask |= exprSelectUsage(pMaskSet, p->x.pSelect); 1813 }else if( p->x.pList ){ 1814 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList); 1815 } 1816 #ifndef SQLITE_OMIT_WINDOWFUNC 1817 if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){ 1818 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition); 1819 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy); 1820 mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter); 1821 } 1822 #endif 1823 return mask; 1824 } 1825 Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){ 1826 return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0; 1827 } 1828 Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){ 1829 int i; 1830 Bitmask mask = 0; 1831 if( pList ){ 1832 for(i=0; i<pList->nExpr; i++){ 1833 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr); 1834 } 1835 } 1836 return mask; 1837 } 1838 1839 1840 /* 1841 ** Call exprAnalyze on all terms in a WHERE clause. 1842 ** 1843 ** Note that exprAnalyze() might add new virtual terms onto the 1844 ** end of the WHERE clause. We do not want to analyze these new 1845 ** virtual terms, so start analyzing at the end and work forward 1846 ** so that the added virtual terms are never processed. 1847 */ 1848 void sqlite3WhereExprAnalyze( 1849 SrcList *pTabList, /* the FROM clause */ 1850 WhereClause *pWC /* the WHERE clause to be analyzed */ 1851 ){ 1852 int i; 1853 for(i=pWC->nTerm-1; i>=0; i--){ 1854 exprAnalyze(pTabList, pWC, i); 1855 } 1856 } 1857 1858 /* 1859 ** For table-valued-functions, transform the function arguments into 1860 ** new WHERE clause terms. 1861 ** 1862 ** Each function argument translates into an equality constraint against 1863 ** a HIDDEN column in the table. 1864 */ 1865 void sqlite3WhereTabFuncArgs( 1866 Parse *pParse, /* Parsing context */ 1867 SrcItem *pItem, /* The FROM clause term to process */ 1868 WhereClause *pWC /* Xfer function arguments to here */ 1869 ){ 1870 Table *pTab; 1871 int j, k; 1872 ExprList *pArgs; 1873 Expr *pColRef; 1874 Expr *pTerm; 1875 if( pItem->fg.isTabFunc==0 ) return; 1876 pTab = pItem->pTab; 1877 assert( pTab!=0 ); 1878 pArgs = pItem->u1.pFuncArg; 1879 if( pArgs==0 ) return; 1880 for(j=k=0; j<pArgs->nExpr; j++){ 1881 Expr *pRhs; 1882 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;} 1883 if( k>=pTab->nCol ){ 1884 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d", 1885 pTab->zName, j); 1886 return; 1887 } 1888 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0); 1889 if( pColRef==0 ) return; 1890 pColRef->iTable = pItem->iCursor; 1891 pColRef->iColumn = k++; 1892 pColRef->y.pTab = pTab; 1893 pRhs = sqlite3PExpr(pParse, TK_UPLUS, 1894 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0); 1895 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs); 1896 if( pItem->fg.jointype & JT_LEFT ){ 1897 sqlite3SetJoinExpr(pTerm, pItem->iCursor); 1898 } 1899 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC); 1900 } 1901 } 1902