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