| OLD | NEW |
| 1 /* | 1 /* |
| 2 ** 2001 September 15 | 2 ** 2001 September 15 |
| 3 ** | 3 ** |
| 4 ** The author disclaims copyright to this source code. In place of | 4 ** The author disclaims copyright to this source code. In place of |
| 5 ** a legal notice, here is a blessing: | 5 ** a legal notice, here is a blessing: |
| 6 ** | 6 ** |
| 7 ** May you do good and not evil. | 7 ** May you do good and not evil. |
| 8 ** May you find forgiveness for yourself and forgive others. | 8 ** May you find forgiveness for yourself and forgive others. |
| 9 ** May you share freely, never taking more than you give. | 9 ** May you share freely, never taking more than you give. |
| 10 ** | 10 ** |
| 11 ************************************************************************* | 11 ************************************************************************* |
| 12 ** This module contains C code that generates VDBE code used to process | 12 ** This module contains C code that generates VDBE code used to process |
| 13 ** the WHERE clause of SQL statements. This module is responsible for | 13 ** the WHERE clause of SQL statements. This module is responsible for |
| 14 ** generating the code that loops through a table looking for applicable | 14 ** generating the code that loops through a table looking for applicable |
| 15 ** rows. Indices are selected and used to speed the search when doing | 15 ** rows. Indices are selected and used to speed the search when doing |
| 16 ** so is applicable. Because this module is responsible for selecting | 16 ** so is applicable. Because this module is responsible for selecting |
| 17 ** indices, you might also think of this module as the "query optimizer". | 17 ** indices, you might also think of this module as the "query optimizer". |
| 18 */ | 18 */ |
| 19 #include "sqliteInt.h" | 19 #include "sqliteInt.h" |
| 20 #include "whereInt.h" | 20 #include "whereInt.h" |
| 21 | 21 |
| 22 /* Forward declaration of methods */ |
| 23 static int whereLoopResize(sqlite3*, WhereLoop*, int); |
| 24 |
| 25 /* Test variable that can be set to enable WHERE tracing */ |
| 26 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) |
| 27 /***/ int sqlite3WhereTrace = 0; |
| 28 #endif |
| 29 |
| 30 |
| 22 /* | 31 /* |
| 23 ** Return the estimated number of output rows from a WHERE clause | 32 ** Return the estimated number of output rows from a WHERE clause |
| 24 */ | 33 */ |
| 25 u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ | 34 u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){ |
| 26 return sqlite3LogEstToInt(pWInfo->nRowOut); | 35 return sqlite3LogEstToInt(pWInfo->nRowOut); |
| 27 } | 36 } |
| 28 | 37 |
| 29 /* | 38 /* |
| 30 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this | 39 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this |
| 31 ** WHERE clause returns outputs for DISTINCT processing. | 40 ** WHERE clause returns outputs for DISTINCT processing. |
| (...skipping 21 matching lines...) Expand all Loading... |
| 53 | 62 |
| 54 /* | 63 /* |
| 55 ** Return the VDBE address or label to jump to in order to break | 64 ** Return the VDBE address or label to jump to in order to break |
| 56 ** out of a WHERE loop. | 65 ** out of a WHERE loop. |
| 57 */ | 66 */ |
| 58 int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ | 67 int sqlite3WhereBreakLabel(WhereInfo *pWInfo){ |
| 59 return pWInfo->iBreak; | 68 return pWInfo->iBreak; |
| 60 } | 69 } |
| 61 | 70 |
| 62 /* | 71 /* |
| 63 ** Return TRUE if an UPDATE or DELETE statement can operate directly on | 72 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to |
| 64 ** the rowids returned by a WHERE clause. Return FALSE if doing an | 73 ** operate directly on the rowis returned by a WHERE clause. Return |
| 65 ** UPDATE or DELETE might change subsequent WHERE clause results. | 74 ** ONEPASS_SINGLE (1) if the statement can operation directly because only |
| 75 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass |
| 76 ** optimization can be used on multiple |
| 66 ** | 77 ** |
| 67 ** If the ONEPASS optimization is used (if this routine returns true) | 78 ** If the ONEPASS optimization is used (if this routine returns true) |
| 68 ** then also write the indices of open cursors used by ONEPASS | 79 ** then also write the indices of open cursors used by ONEPASS |
| 69 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data | 80 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data |
| 70 ** table and iaCur[1] gets the cursor used by an auxiliary index. | 81 ** table and iaCur[1] gets the cursor used by an auxiliary index. |
| 71 ** Either value may be -1, indicating that cursor is not used. | 82 ** Either value may be -1, indicating that cursor is not used. |
| 72 ** Any cursors returned will have been opened for writing. | 83 ** Any cursors returned will have been opened for writing. |
| 73 ** | 84 ** |
| 74 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is | 85 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is |
| 75 ** unable to use the ONEPASS optimization. | 86 ** unable to use the ONEPASS optimization. |
| 76 */ | 87 */ |
| 77 int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ | 88 int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){ |
| 78 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); | 89 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2); |
| 79 return pWInfo->okOnePass; | 90 #ifdef WHERETRACE_ENABLED |
| 91 if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){ |
| 92 sqlite3DebugPrintf("%s cursors: %d %d\n", |
| 93 pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI", |
| 94 aiCur[0], aiCur[1]); |
| 95 } |
| 96 #endif |
| 97 return pWInfo->eOnePass; |
| 80 } | 98 } |
| 81 | 99 |
| 82 /* | 100 /* |
| 83 ** Move the content of pSrc into pDest | 101 ** Move the content of pSrc into pDest |
| 84 */ | 102 */ |
| 85 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ | 103 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){ |
| 86 pDest->n = pSrc->n; | 104 pDest->n = pSrc->n; |
| 87 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); | 105 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0])); |
| 88 } | 106 } |
| 89 | 107 |
| (...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 121 if( p->rRun<=rRun ) return 0; | 139 if( p->rRun<=rRun ) return 0; |
| 122 } | 140 } |
| 123 whereOrInsert_done: | 141 whereOrInsert_done: |
| 124 p->prereq = prereq; | 142 p->prereq = prereq; |
| 125 p->rRun = rRun; | 143 p->rRun = rRun; |
| 126 if( p->nOut>nOut ) p->nOut = nOut; | 144 if( p->nOut>nOut ) p->nOut = nOut; |
| 127 return 1; | 145 return 1; |
| 128 } | 146 } |
| 129 | 147 |
| 130 /* | 148 /* |
| 131 ** Initialize a preallocated WhereClause structure. | |
| 132 */ | |
| 133 static void whereClauseInit( | |
| 134 WhereClause *pWC, /* The WhereClause to be initialized */ | |
| 135 WhereInfo *pWInfo /* The WHERE processing context */ | |
| 136 ){ | |
| 137 pWC->pWInfo = pWInfo; | |
| 138 pWC->pOuter = 0; | |
| 139 pWC->nTerm = 0; | |
| 140 pWC->nSlot = ArraySize(pWC->aStatic); | |
| 141 pWC->a = pWC->aStatic; | |
| 142 } | |
| 143 | |
| 144 /* Forward reference */ | |
| 145 static void whereClauseClear(WhereClause*); | |
| 146 | |
| 147 /* | |
| 148 ** Deallocate all memory associated with a WhereOrInfo object. | |
| 149 */ | |
| 150 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){ | |
| 151 whereClauseClear(&p->wc); | |
| 152 sqlite3DbFree(db, p); | |
| 153 } | |
| 154 | |
| 155 /* | |
| 156 ** Deallocate all memory associated with a WhereAndInfo object. | |
| 157 */ | |
| 158 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){ | |
| 159 whereClauseClear(&p->wc); | |
| 160 sqlite3DbFree(db, p); | |
| 161 } | |
| 162 | |
| 163 /* | |
| 164 ** Deallocate a WhereClause structure. The WhereClause structure | |
| 165 ** itself is not freed. This routine is the inverse of whereClauseInit(). | |
| 166 */ | |
| 167 static void whereClauseClear(WhereClause *pWC){ | |
| 168 int i; | |
| 169 WhereTerm *a; | |
| 170 sqlite3 *db = pWC->pWInfo->pParse->db; | |
| 171 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){ | |
| 172 if( a->wtFlags & TERM_DYNAMIC ){ | |
| 173 sqlite3ExprDelete(db, a->pExpr); | |
| 174 } | |
| 175 if( a->wtFlags & TERM_ORINFO ){ | |
| 176 whereOrInfoDelete(db, a->u.pOrInfo); | |
| 177 }else if( a->wtFlags & TERM_ANDINFO ){ | |
| 178 whereAndInfoDelete(db, a->u.pAndInfo); | |
| 179 } | |
| 180 } | |
| 181 if( pWC->a!=pWC->aStatic ){ | |
| 182 sqlite3DbFree(db, pWC->a); | |
| 183 } | |
| 184 } | |
| 185 | |
| 186 /* | |
| 187 ** Add a single new WhereTerm entry to the WhereClause object pWC. | |
| 188 ** The new WhereTerm object is constructed from Expr p and with wtFlags. | |
| 189 ** The index in pWC->a[] of the new WhereTerm is returned on success. | |
| 190 ** 0 is returned if the new WhereTerm could not be added due to a memory | |
| 191 ** allocation error. The memory allocation failure will be recorded in | |
| 192 ** the db->mallocFailed flag so that higher-level functions can detect it. | |
| 193 ** | |
| 194 ** This routine will increase the size of the pWC->a[] array as necessary. | |
| 195 ** | |
| 196 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility | |
| 197 ** for freeing the expression p is assumed by the WhereClause object pWC. | |
| 198 ** This is true even if this routine fails to allocate a new WhereTerm. | |
| 199 ** | |
| 200 ** WARNING: This routine might reallocate the space used to store | |
| 201 ** WhereTerms. All pointers to WhereTerms should be invalidated after | |
| 202 ** calling this routine. Such pointers may be reinitialized by referencing | |
| 203 ** the pWC->a[] array. | |
| 204 */ | |
| 205 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){ | |
| 206 WhereTerm *pTerm; | |
| 207 int idx; | |
| 208 testcase( wtFlags & TERM_VIRTUAL ); | |
| 209 if( pWC->nTerm>=pWC->nSlot ){ | |
| 210 WhereTerm *pOld = pWC->a; | |
| 211 sqlite3 *db = pWC->pWInfo->pParse->db; | |
| 212 pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 ); | |
| 213 if( pWC->a==0 ){ | |
| 214 if( wtFlags & TERM_DYNAMIC ){ | |
| 215 sqlite3ExprDelete(db, p); | |
| 216 } | |
| 217 pWC->a = pOld; | |
| 218 return 0; | |
| 219 } | |
| 220 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); | |
| 221 if( pOld!=pWC->aStatic ){ | |
| 222 sqlite3DbFree(db, pOld); | |
| 223 } | |
| 224 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]); | |
| 225 } | |
| 226 pTerm = &pWC->a[idx = pWC->nTerm++]; | |
| 227 if( p && ExprHasProperty(p, EP_Unlikely) ){ | |
| 228 pTerm->truthProb = sqlite3LogEst(p->iTable) - 99; | |
| 229 }else{ | |
| 230 pTerm->truthProb = 1; | |
| 231 } | |
| 232 pTerm->pExpr = sqlite3ExprSkipCollate(p); | |
| 233 pTerm->wtFlags = wtFlags; | |
| 234 pTerm->pWC = pWC; | |
| 235 pTerm->iParent = -1; | |
| 236 return idx; | |
| 237 } | |
| 238 | |
| 239 /* | |
| 240 ** This routine identifies subexpressions in the WHERE clause where | |
| 241 ** each subexpression is separated by the AND operator or some other | |
| 242 ** operator specified in the op parameter. The WhereClause structure | |
| 243 ** is filled with pointers to subexpressions. For example: | |
| 244 ** | |
| 245 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22) | |
| 246 ** \________/ \_______________/ \________________/ | |
| 247 ** slot[0] slot[1] slot[2] | |
| 248 ** | |
| 249 ** The original WHERE clause in pExpr is unaltered. All this routine | |
| 250 ** does is make slot[] entries point to substructure within pExpr. | |
| 251 ** | |
| 252 ** In the previous sentence and in the diagram, "slot[]" refers to | |
| 253 ** the WhereClause.a[] array. The slot[] array grows as needed to contain | |
| 254 ** all terms of the WHERE clause. | |
| 255 */ | |
| 256 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){ | |
| 257 pWC->op = op; | |
| 258 if( pExpr==0 ) return; | |
| 259 if( pExpr->op!=op ){ | |
| 260 whereClauseInsert(pWC, pExpr, 0); | |
| 261 }else{ | |
| 262 whereSplit(pWC, pExpr->pLeft, op); | |
| 263 whereSplit(pWC, pExpr->pRight, op); | |
| 264 } | |
| 265 } | |
| 266 | |
| 267 /* | |
| 268 ** Initialize a WhereMaskSet object | |
| 269 */ | |
| 270 #define initMaskSet(P) (P)->n=0 | |
| 271 | |
| 272 /* | |
| 273 ** Return the bitmask for the given cursor number. Return 0 if | 149 ** Return the bitmask for the given cursor number. Return 0 if |
| 274 ** iCursor is not in the set. | 150 ** iCursor is not in the set. |
| 275 */ | 151 */ |
| 276 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){ | 152 Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){ |
| 277 int i; | 153 int i; |
| 278 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); | 154 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 ); |
| 279 for(i=0; i<pMaskSet->n; i++){ | 155 for(i=0; i<pMaskSet->n; i++){ |
| 280 if( pMaskSet->ix[i]==iCursor ){ | 156 if( pMaskSet->ix[i]==iCursor ){ |
| 281 return MASKBIT(i); | 157 return MASKBIT(i); |
| 282 } | 158 } |
| 283 } | 159 } |
| 284 return 0; | 160 return 0; |
| 285 } | 161 } |
| 286 | 162 |
| 287 /* | 163 /* |
| 288 ** Create a new mask for cursor iCursor. | 164 ** Create a new mask for cursor iCursor. |
| 289 ** | 165 ** |
| 290 ** There is one cursor per table in the FROM clause. The number of | 166 ** There is one cursor per table in the FROM clause. The number of |
| 291 ** tables in the FROM clause is limited by a test early in the | 167 ** tables in the FROM clause is limited by a test early in the |
| 292 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] | 168 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[] |
| 293 ** array will never overflow. | 169 ** array will never overflow. |
| 294 */ | 170 */ |
| 295 static void createMask(WhereMaskSet *pMaskSet, int iCursor){ | 171 static void createMask(WhereMaskSet *pMaskSet, int iCursor){ |
| 296 assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); | 172 assert( pMaskSet->n < ArraySize(pMaskSet->ix) ); |
| 297 pMaskSet->ix[pMaskSet->n++] = iCursor; | 173 pMaskSet->ix[pMaskSet->n++] = iCursor; |
| 298 } | 174 } |
| 299 | 175 |
| 300 /* | 176 /* |
| 301 ** These routines walk (recursively) an expression tree and generate | |
| 302 ** a bitmask indicating which tables are used in that expression | |
| 303 ** tree. | |
| 304 */ | |
| 305 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*); | |
| 306 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*); | |
| 307 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){ | |
| 308 Bitmask mask = 0; | |
| 309 if( p==0 ) return 0; | |
| 310 if( p->op==TK_COLUMN ){ | |
| 311 mask = getMask(pMaskSet, p->iTable); | |
| 312 return mask; | |
| 313 } | |
| 314 mask = exprTableUsage(pMaskSet, p->pRight); | |
| 315 mask |= exprTableUsage(pMaskSet, p->pLeft); | |
| 316 if( ExprHasProperty(p, EP_xIsSelect) ){ | |
| 317 mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect); | |
| 318 }else{ | |
| 319 mask |= exprListTableUsage(pMaskSet, p->x.pList); | |
| 320 } | |
| 321 return mask; | |
| 322 } | |
| 323 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){ | |
| 324 int i; | |
| 325 Bitmask mask = 0; | |
| 326 if( pList ){ | |
| 327 for(i=0; i<pList->nExpr; i++){ | |
| 328 mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr); | |
| 329 } | |
| 330 } | |
| 331 return mask; | |
| 332 } | |
| 333 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){ | |
| 334 Bitmask mask = 0; | |
| 335 while( pS ){ | |
| 336 SrcList *pSrc = pS->pSrc; | |
| 337 mask |= exprListTableUsage(pMaskSet, pS->pEList); | |
| 338 mask |= exprListTableUsage(pMaskSet, pS->pGroupBy); | |
| 339 mask |= exprListTableUsage(pMaskSet, pS->pOrderBy); | |
| 340 mask |= exprTableUsage(pMaskSet, pS->pWhere); | |
| 341 mask |= exprTableUsage(pMaskSet, pS->pHaving); | |
| 342 if( ALWAYS(pSrc!=0) ){ | |
| 343 int i; | |
| 344 for(i=0; i<pSrc->nSrc; i++){ | |
| 345 mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect); | |
| 346 mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn); | |
| 347 } | |
| 348 } | |
| 349 pS = pS->pPrior; | |
| 350 } | |
| 351 return mask; | |
| 352 } | |
| 353 | |
| 354 /* | |
| 355 ** Return TRUE if the given operator is one of the operators that is | |
| 356 ** allowed for an indexable WHERE clause term. The allowed operators are | |
| 357 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL" | |
| 358 */ | |
| 359 static int allowedOp(int op){ | |
| 360 assert( TK_GT>TK_EQ && TK_GT<TK_GE ); | |
| 361 assert( TK_LT>TK_EQ && TK_LT<TK_GE ); | |
| 362 assert( TK_LE>TK_EQ && TK_LE<TK_GE ); | |
| 363 assert( TK_GE==TK_EQ+4 ); | |
| 364 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL; | |
| 365 } | |
| 366 | |
| 367 /* | |
| 368 ** Commute a comparison operator. Expressions of the form "X op Y" | |
| 369 ** are converted into "Y op X". | |
| 370 ** | |
| 371 ** If left/right precedence rules come into play when determining the | |
| 372 ** collating sequence, then COLLATE operators are adjusted to ensure | |
| 373 ** that the collating sequence does not change. For example: | |
| 374 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on | |
| 375 ** the left hand side of a comparison overrides any collation sequence | |
| 376 ** attached to the right. For the same reason the EP_Collate flag | |
| 377 ** is not commuted. | |
| 378 */ | |
| 379 static void exprCommute(Parse *pParse, Expr *pExpr){ | |
| 380 u16 expRight = (pExpr->pRight->flags & EP_Collate); | |
| 381 u16 expLeft = (pExpr->pLeft->flags & EP_Collate); | |
| 382 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN ); | |
| 383 if( expRight==expLeft ){ | |
| 384 /* Either X and Y both have COLLATE operator or neither do */ | |
| 385 if( expRight ){ | |
| 386 /* Both X and Y have COLLATE operators. Make sure X is always | |
| 387 ** used by clearing the EP_Collate flag from Y. */ | |
| 388 pExpr->pRight->flags &= ~EP_Collate; | |
| 389 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){ | |
| 390 /* Neither X nor Y have COLLATE operators, but X has a non-default | |
| 391 ** collating sequence. So add the EP_Collate marker on X to cause | |
| 392 ** it to be searched first. */ | |
| 393 pExpr->pLeft->flags |= EP_Collate; | |
| 394 } | |
| 395 } | |
| 396 SWAP(Expr*,pExpr->pRight,pExpr->pLeft); | |
| 397 if( pExpr->op>=TK_GT ){ | |
| 398 assert( TK_LT==TK_GT+2 ); | |
| 399 assert( TK_GE==TK_LE+2 ); | |
| 400 assert( TK_GT>TK_EQ ); | |
| 401 assert( TK_GT<TK_LE ); | |
| 402 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE ); | |
| 403 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT; | |
| 404 } | |
| 405 } | |
| 406 | |
| 407 /* | |
| 408 ** Translate from TK_xx operator to WO_xx bitmask. | |
| 409 */ | |
| 410 static u16 operatorMask(int op){ | |
| 411 u16 c; | |
| 412 assert( allowedOp(op) ); | |
| 413 if( op==TK_IN ){ | |
| 414 c = WO_IN; | |
| 415 }else if( op==TK_ISNULL ){ | |
| 416 c = WO_ISNULL; | |
| 417 }else{ | |
| 418 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff ); | |
| 419 c = (u16)(WO_EQ<<(op-TK_EQ)); | |
| 420 } | |
| 421 assert( op!=TK_ISNULL || c==WO_ISNULL ); | |
| 422 assert( op!=TK_IN || c==WO_IN ); | |
| 423 assert( op!=TK_EQ || c==WO_EQ ); | |
| 424 assert( op!=TK_LT || c==WO_LT ); | |
| 425 assert( op!=TK_LE || c==WO_LE ); | |
| 426 assert( op!=TK_GT || c==WO_GT ); | |
| 427 assert( op!=TK_GE || c==WO_GE ); | |
| 428 return c; | |
| 429 } | |
| 430 | |
| 431 /* | |
| 432 ** Advance to the next WhereTerm that matches according to the criteria | 177 ** Advance to the next WhereTerm that matches according to the criteria |
| 433 ** established when the pScan object was initialized by whereScanInit(). | 178 ** established when the pScan object was initialized by whereScanInit(). |
| 434 ** Return NULL if there are no more matching WhereTerms. | 179 ** Return NULL if there are no more matching WhereTerms. |
| 435 */ | 180 */ |
| 436 static WhereTerm *whereScanNext(WhereScan *pScan){ | 181 static WhereTerm *whereScanNext(WhereScan *pScan){ |
| 437 int iCur; /* The cursor on the LHS of the term */ | 182 int iCur; /* The cursor on the LHS of the term */ |
| 438 int iColumn; /* The column on the LHS of the term. -1 for IPK */ | 183 i16 iColumn; /* The column on the LHS of the term. -1 for IPK */ |
| 439 Expr *pX; /* An expression being tested */ | 184 Expr *pX; /* An expression being tested */ |
| 440 WhereClause *pWC; /* Shorthand for pScan->pWC */ | 185 WhereClause *pWC; /* Shorthand for pScan->pWC */ |
| 441 WhereTerm *pTerm; /* The term being tested */ | 186 WhereTerm *pTerm; /* The term being tested */ |
| 442 int k = pScan->k; /* Where to start scanning */ | 187 int k = pScan->k; /* Where to start scanning */ |
| 443 | 188 |
| 444 while( pScan->iEquiv<=pScan->nEquiv ){ | 189 while( pScan->iEquiv<=pScan->nEquiv ){ |
| 445 iCur = pScan->aEquiv[pScan->iEquiv-2]; | 190 iCur = pScan->aiCur[pScan->iEquiv-1]; |
| 446 iColumn = pScan->aEquiv[pScan->iEquiv-1]; | 191 iColumn = pScan->aiColumn[pScan->iEquiv-1]; |
| 192 if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0; |
| 447 while( (pWC = pScan->pWC)!=0 ){ | 193 while( (pWC = pScan->pWC)!=0 ){ |
| 448 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){ | 194 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){ |
| 449 if( pTerm->leftCursor==iCur | 195 if( pTerm->leftCursor==iCur |
| 450 && pTerm->u.leftColumn==iColumn | 196 && pTerm->u.leftColumn==iColumn |
| 451 && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin)) | 197 && (iColumn!=XN_EXPR |
| 198 || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0) |
| 199 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin)) |
| 452 ){ | 200 ){ |
| 453 if( (pTerm->eOperator & WO_EQUIV)!=0 | 201 if( (pTerm->eOperator & WO_EQUIV)!=0 |
| 454 && pScan->nEquiv<ArraySize(pScan->aEquiv) | 202 && pScan->nEquiv<ArraySize(pScan->aiCur) |
| 203 && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN |
| 455 ){ | 204 ){ |
| 456 int j; | 205 int j; |
| 457 pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight); | 206 for(j=0; j<pScan->nEquiv; j++){ |
| 458 assert( pX->op==TK_COLUMN ); | 207 if( pScan->aiCur[j]==pX->iTable |
| 459 for(j=0; j<pScan->nEquiv; j+=2){ | 208 && pScan->aiColumn[j]==pX->iColumn ){ |
| 460 if( pScan->aEquiv[j]==pX->iTable | |
| 461 && pScan->aEquiv[j+1]==pX->iColumn ){ | |
| 462 break; | 209 break; |
| 463 } | 210 } |
| 464 } | 211 } |
| 465 if( j==pScan->nEquiv ){ | 212 if( j==pScan->nEquiv ){ |
| 466 pScan->aEquiv[j] = pX->iTable; | 213 pScan->aiCur[j] = pX->iTable; |
| 467 pScan->aEquiv[j+1] = pX->iColumn; | 214 pScan->aiColumn[j] = pX->iColumn; |
| 468 pScan->nEquiv += 2; | 215 pScan->nEquiv++; |
| 469 } | 216 } |
| 470 } | 217 } |
| 471 if( (pTerm->eOperator & pScan->opMask)!=0 ){ | 218 if( (pTerm->eOperator & pScan->opMask)!=0 ){ |
| 472 /* Verify the affinity and collating sequence match */ | 219 /* Verify the affinity and collating sequence match */ |
| 473 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ | 220 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){ |
| 474 CollSeq *pColl; | 221 CollSeq *pColl; |
| 475 Parse *pParse = pWC->pWInfo->pParse; | 222 Parse *pParse = pWC->pWInfo->pParse; |
| 476 pX = pTerm->pExpr; | 223 pX = pTerm->pExpr; |
| 477 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ | 224 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){ |
| 478 continue; | 225 continue; |
| 479 } | 226 } |
| 480 assert(pX->pLeft); | 227 assert(pX->pLeft); |
| 481 pColl = sqlite3BinaryCompareCollSeq(pParse, | 228 pColl = sqlite3BinaryCompareCollSeq(pParse, |
| 482 pX->pLeft, pX->pRight); | 229 pX->pLeft, pX->pRight); |
| 483 if( pColl==0 ) pColl = pParse->db->pDfltColl; | 230 if( pColl==0 ) pColl = pParse->db->pDfltColl; |
| 484 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ | 231 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){ |
| 485 continue; | 232 continue; |
| 486 } | 233 } |
| 487 } | 234 } |
| 488 if( (pTerm->eOperator & WO_EQ)!=0 | 235 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0 |
| 489 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN | 236 && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN |
| 490 && pX->iTable==pScan->aEquiv[0] | 237 && pX->iTable==pScan->aiCur[0] |
| 491 && pX->iColumn==pScan->aEquiv[1] | 238 && pX->iColumn==pScan->aiColumn[0] |
| 492 ){ | 239 ){ |
| 240 testcase( pTerm->eOperator & WO_IS ); |
| 493 continue; | 241 continue; |
| 494 } | 242 } |
| 495 pScan->k = k+1; | 243 pScan->k = k+1; |
| 496 return pTerm; | 244 return pTerm; |
| 497 } | 245 } |
| 498 } | 246 } |
| 499 } | 247 } |
| 500 pScan->pWC = pScan->pWC->pOuter; | 248 pScan->pWC = pScan->pWC->pOuter; |
| 501 k = 0; | 249 k = 0; |
| 502 } | 250 } |
| 503 pScan->pWC = pScan->pOrigWC; | 251 pScan->pWC = pScan->pOrigWC; |
| 504 k = 0; | 252 k = 0; |
| 505 pScan->iEquiv += 2; | 253 pScan->iEquiv++; |
| 506 } | 254 } |
| 507 return 0; | 255 return 0; |
| 508 } | 256 } |
| 509 | 257 |
| 510 /* | 258 /* |
| 511 ** Initialize a WHERE clause scanner object. Return a pointer to the | 259 ** Initialize a WHERE clause scanner object. Return a pointer to the |
| 512 ** first match. Return NULL if there are no matches. | 260 ** first match. Return NULL if there are no matches. |
| 513 ** | 261 ** |
| 514 ** The scanner will be searching the WHERE clause pWC. It will look | 262 ** The scanner will be searching the WHERE clause pWC. It will look |
| 515 ** for terms of the form "X <op> <expr>" where X is column iColumn of table | 263 ** for terms of the form "X <op> <expr>" where X is column iColumn of table |
| 516 ** iCur. The <op> must be one of the operators described by opMask. | 264 ** iCur. The <op> must be one of the operators described by opMask. |
| 517 ** | 265 ** |
| 518 ** If the search is for X and the WHERE clause contains terms of the | 266 ** If the search is for X and the WHERE clause contains terms of the |
| 519 ** form X=Y then this routine might also return terms of the form | 267 ** form X=Y then this routine might also return terms of the form |
| 520 ** "Y <op> <expr>". The number of levels of transitivity is limited, | 268 ** "Y <op> <expr>". The number of levels of transitivity is limited, |
| 521 ** but is enough to handle most commonly occurring SQL statements. | 269 ** but is enough to handle most commonly occurring SQL statements. |
| 522 ** | 270 ** |
| 523 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with | 271 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with |
| 524 ** index pIdx. | 272 ** index pIdx. |
| 525 */ | 273 */ |
| 526 static WhereTerm *whereScanInit( | 274 static WhereTerm *whereScanInit( |
| 527 WhereScan *pScan, /* The WhereScan object being initialized */ | 275 WhereScan *pScan, /* The WhereScan object being initialized */ |
| 528 WhereClause *pWC, /* The WHERE clause to be scanned */ | 276 WhereClause *pWC, /* The WHERE clause to be scanned */ |
| 529 int iCur, /* Cursor to scan for */ | 277 int iCur, /* Cursor to scan for */ |
| 530 int iColumn, /* Column to scan for */ | 278 int iColumn, /* Column to scan for */ |
| 531 u32 opMask, /* Operator(s) to scan for */ | 279 u32 opMask, /* Operator(s) to scan for */ |
| 532 Index *pIdx /* Must be compatible with this index */ | 280 Index *pIdx /* Must be compatible with this index */ |
| 533 ){ | 281 ){ |
| 534 int j; | 282 int j = 0; |
| 535 | 283 |
| 536 /* memset(pScan, 0, sizeof(*pScan)); */ | 284 /* memset(pScan, 0, sizeof(*pScan)); */ |
| 537 pScan->pOrigWC = pWC; | 285 pScan->pOrigWC = pWC; |
| 538 pScan->pWC = pWC; | 286 pScan->pWC = pWC; |
| 287 pScan->pIdxExpr = 0; |
| 288 if( pIdx ){ |
| 289 j = iColumn; |
| 290 iColumn = pIdx->aiColumn[j]; |
| 291 if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr; |
| 292 } |
| 539 if( pIdx && iColumn>=0 ){ | 293 if( pIdx && iColumn>=0 ){ |
| 540 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; | 294 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity; |
| 541 for(j=0; pIdx->aiColumn[j]!=iColumn; j++){ | |
| 542 if( NEVER(j>pIdx->nColumn) ) return 0; | |
| 543 } | |
| 544 pScan->zCollName = pIdx->azColl[j]; | 295 pScan->zCollName = pIdx->azColl[j]; |
| 545 }else{ | 296 }else{ |
| 546 pScan->idxaff = 0; | 297 pScan->idxaff = 0; |
| 547 pScan->zCollName = 0; | 298 pScan->zCollName = 0; |
| 548 } | 299 } |
| 549 pScan->opMask = opMask; | 300 pScan->opMask = opMask; |
| 550 pScan->k = 0; | 301 pScan->k = 0; |
| 551 pScan->aEquiv[0] = iCur; | 302 pScan->aiCur[0] = iCur; |
| 552 pScan->aEquiv[1] = iColumn; | 303 pScan->aiColumn[0] = iColumn; |
| 553 pScan->nEquiv = 2; | 304 pScan->nEquiv = 1; |
| 554 pScan->iEquiv = 2; | 305 pScan->iEquiv = 1; |
| 555 return whereScanNext(pScan); | 306 return whereScanNext(pScan); |
| 556 } | 307 } |
| 557 | 308 |
| 558 /* | 309 /* |
| 559 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>" | 310 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>" |
| 560 ** where X is a reference to the iColumn of table iCur and <op> is one of | 311 ** where X is a reference to the iColumn of table iCur and <op> is one of |
| 561 ** the WO_xx operator codes specified by the op parameter. | 312 ** the WO_xx operator codes specified by the op parameter. |
| 562 ** Return a pointer to the term. Return 0 if not found. | 313 ** Return a pointer to the term. Return 0 if not found. |
| 563 ** | 314 ** |
| 315 ** If pIdx!=0 then search for terms matching the iColumn-th column of pIdx |
| 316 ** rather than the iColumn-th column of table iCur. |
| 317 ** |
| 564 ** The term returned might by Y=<expr> if there is another constraint in | 318 ** The term returned might by Y=<expr> if there is another constraint in |
| 565 ** the WHERE clause that specifies that X=Y. Any such constraints will be | 319 ** the WHERE clause that specifies that X=Y. Any such constraints will be |
| 566 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The | 320 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The |
| 567 ** aEquiv[] array holds X and all its equivalents, with each SQL variable | 321 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11 |
| 568 ** taking up two slots in aEquiv[]. The first slot is for the cursor number | 322 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10 |
| 569 ** and the second is for the column number. There are 22 slots in aEquiv[] | 323 ** other equivalent values. Hence a search for X will return <expr> if X=A1 |
| 570 ** so that means we can look for X plus up to 10 other equivalent values. | 324 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>. |
| 571 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3 | |
| 572 ** and ... and A9=A10 and A10=<expr>. | |
| 573 ** | 325 ** |
| 574 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>" | 326 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>" |
| 575 ** then try for the one with no dependencies on <expr> - in other words where | 327 ** then try for the one with no dependencies on <expr> - in other words where |
| 576 ** <expr> is a constant expression of some kind. Only return entries of | 328 ** <expr> is a constant expression of some kind. Only return entries of |
| 577 ** the form "X <op> Y" where Y is a column in another table if no terms of | 329 ** the form "X <op> Y" where Y is a column in another table if no terms of |
| 578 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS | 330 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS |
| 579 ** exist, try to return a term that does not use WO_EQUIV. | 331 ** exist, try to return a term that does not use WO_EQUIV. |
| 580 */ | 332 */ |
| 581 static WhereTerm *findTerm( | 333 WhereTerm *sqlite3WhereFindTerm( |
| 582 WhereClause *pWC, /* The WHERE clause to be searched */ | 334 WhereClause *pWC, /* The WHERE clause to be searched */ |
| 583 int iCur, /* Cursor number of LHS */ | 335 int iCur, /* Cursor number of LHS */ |
| 584 int iColumn, /* Column number of LHS */ | 336 int iColumn, /* Column number of LHS */ |
| 585 Bitmask notReady, /* RHS must not overlap with this mask */ | 337 Bitmask notReady, /* RHS must not overlap with this mask */ |
| 586 u32 op, /* Mask of WO_xx values describing operator */ | 338 u32 op, /* Mask of WO_xx values describing operator */ |
| 587 Index *pIdx /* Must be compatible with this index, if not NULL */ | 339 Index *pIdx /* Must be compatible with this index, if not NULL */ |
| 588 ){ | 340 ){ |
| 589 WhereTerm *pResult = 0; | 341 WhereTerm *pResult = 0; |
| 590 WhereTerm *p; | 342 WhereTerm *p; |
| 591 WhereScan scan; | 343 WhereScan scan; |
| 592 | 344 |
| 593 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); | 345 p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx); |
| 346 op &= WO_EQ|WO_IS; |
| 594 while( p ){ | 347 while( p ){ |
| 595 if( (p->prereqRight & notReady)==0 ){ | 348 if( (p->prereqRight & notReady)==0 ){ |
| 596 if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){ | 349 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){ |
| 350 testcase( p->eOperator & WO_IS ); |
| 597 return p; | 351 return p; |
| 598 } | 352 } |
| 599 if( pResult==0 ) pResult = p; | 353 if( pResult==0 ) pResult = p; |
| 600 } | 354 } |
| 601 p = whereScanNext(&scan); | 355 p = whereScanNext(&scan); |
| 602 } | 356 } |
| 603 return pResult; | 357 return pResult; |
| 604 } | 358 } |
| 605 | 359 |
| 606 /* Forward reference */ | |
| 607 static void exprAnalyze(SrcList*, WhereClause*, int); | |
| 608 | |
| 609 /* | |
| 610 ** Call exprAnalyze on all terms in a WHERE clause. | |
| 611 */ | |
| 612 static void exprAnalyzeAll( | |
| 613 SrcList *pTabList, /* the FROM clause */ | |
| 614 WhereClause *pWC /* the WHERE clause to be analyzed */ | |
| 615 ){ | |
| 616 int i; | |
| 617 for(i=pWC->nTerm-1; i>=0; i--){ | |
| 618 exprAnalyze(pTabList, pWC, i); | |
| 619 } | |
| 620 } | |
| 621 | |
| 622 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION | |
| 623 /* | |
| 624 ** Check to see if the given expression is a LIKE or GLOB operator that | |
| 625 ** can be optimized using inequality constraints. Return TRUE if it is | |
| 626 ** so and false if not. | |
| 627 ** | |
| 628 ** In order for the operator to be optimizible, the RHS must be a string | |
| 629 ** literal that does not begin with a wildcard. | |
| 630 */ | |
| 631 static int isLikeOrGlob( | |
| 632 Parse *pParse, /* Parsing and code generating context */ | |
| 633 Expr *pExpr, /* Test this expression */ | |
| 634 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */ | |
| 635 int *pisComplete, /* True if the only wildcard is % in the last character */ | |
| 636 int *pnoCase /* True if uppercase is equivalent to lowercase */ | |
| 637 ){ | |
| 638 const char *z = 0; /* String on RHS of LIKE operator */ | |
| 639 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */ | |
| 640 ExprList *pList; /* List of operands to the LIKE operator */ | |
| 641 int c; /* One character in z[] */ | |
| 642 int cnt; /* Number of non-wildcard prefix characters */ | |
| 643 char wc[3]; /* Wildcard characters */ | |
| 644 sqlite3 *db = pParse->db; /* Database connection */ | |
| 645 sqlite3_value *pVal = 0; | |
| 646 int op; /* Opcode of pRight */ | |
| 647 | |
| 648 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){ | |
| 649 return 0; | |
| 650 } | |
| 651 #ifdef SQLITE_EBCDIC | |
| 652 if( *pnoCase ) return 0; | |
| 653 #endif | |
| 654 pList = pExpr->x.pList; | |
| 655 pLeft = pList->a[1].pExpr; | |
| 656 if( pLeft->op!=TK_COLUMN | |
| 657 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT | |
| 658 || IsVirtual(pLeft->pTab) | |
| 659 ){ | |
| 660 /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must | |
| 661 ** be the name of an indexed column with TEXT affinity. */ | |
| 662 return 0; | |
| 663 } | |
| 664 assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */ | |
| 665 | |
| 666 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr); | |
| 667 op = pRight->op; | |
| 668 if( op==TK_VARIABLE ){ | |
| 669 Vdbe *pReprepare = pParse->pReprepare; | |
| 670 int iCol = pRight->iColumn; | |
| 671 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE); | |
| 672 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){ | |
| 673 z = (char *)sqlite3_value_text(pVal); | |
| 674 } | |
| 675 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol); | |
| 676 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER ); | |
| 677 }else if( op==TK_STRING ){ | |
| 678 z = pRight->u.zToken; | |
| 679 } | |
| 680 if( z ){ | |
| 681 cnt = 0; | |
| 682 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ | |
| 683 cnt++; | |
| 684 } | |
| 685 if( cnt!=0 && 255!=(u8)z[cnt-1] ){ | |
| 686 Expr *pPrefix; | |
| 687 *pisComplete = c==wc[0] && z[cnt+1]==0; | |
| 688 pPrefix = sqlite3Expr(db, TK_STRING, z); | |
| 689 if( pPrefix ) pPrefix->u.zToken[cnt] = 0; | |
| 690 *ppPrefix = pPrefix; | |
| 691 if( op==TK_VARIABLE ){ | |
| 692 Vdbe *v = pParse->pVdbe; | |
| 693 sqlite3VdbeSetVarmask(v, pRight->iColumn); | |
| 694 if( *pisComplete && pRight->u.zToken[1] ){ | |
| 695 /* If the rhs of the LIKE expression is a variable, and the current | |
| 696 ** value of the variable means there is no need to invoke the LIKE | |
| 697 ** function, then no OP_Variable will be added to the program. | |
| 698 ** This causes problems for the sqlite3_bind_parameter_name() | |
| 699 ** API. To work around them, add a dummy OP_Variable here. | |
| 700 */ | |
| 701 int r1 = sqlite3GetTempReg(pParse); | |
| 702 sqlite3ExprCodeTarget(pParse, pRight, r1); | |
| 703 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0); | |
| 704 sqlite3ReleaseTempReg(pParse, r1); | |
| 705 } | |
| 706 } | |
| 707 }else{ | |
| 708 z = 0; | |
| 709 } | |
| 710 } | |
| 711 | |
| 712 sqlite3ValueFree(pVal); | |
| 713 return (z!=0); | |
| 714 } | |
| 715 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ | |
| 716 | |
| 717 | |
| 718 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 719 /* | |
| 720 ** Check to see if the given expression is of the form | |
| 721 ** | |
| 722 ** column MATCH expr | |
| 723 ** | |
| 724 ** If it is then return TRUE. If not, return FALSE. | |
| 725 */ | |
| 726 static int isMatchOfColumn( | |
| 727 Expr *pExpr /* Test this expression */ | |
| 728 ){ | |
| 729 ExprList *pList; | |
| 730 | |
| 731 if( pExpr->op!=TK_FUNCTION ){ | |
| 732 return 0; | |
| 733 } | |
| 734 if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){ | |
| 735 return 0; | |
| 736 } | |
| 737 pList = pExpr->x.pList; | |
| 738 if( pList->nExpr!=2 ){ | |
| 739 return 0; | |
| 740 } | |
| 741 if( pList->a[1].pExpr->op != TK_COLUMN ){ | |
| 742 return 0; | |
| 743 } | |
| 744 return 1; | |
| 745 } | |
| 746 #endif /* SQLITE_OMIT_VIRTUALTABLE */ | |
| 747 | |
| 748 /* | |
| 749 ** If the pBase expression originated in the ON or USING clause of | |
| 750 ** a join, then transfer the appropriate markings over to derived. | |
| 751 */ | |
| 752 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ | |
| 753 if( pDerived ){ | |
| 754 pDerived->flags |= pBase->flags & EP_FromJoin; | |
| 755 pDerived->iRightJoinTable = pBase->iRightJoinTable; | |
| 756 } | |
| 757 } | |
| 758 | |
| 759 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) | |
| 760 /* | |
| 761 ** Analyze a term that consists of two or more OR-connected | |
| 762 ** subterms. So in: | |
| 763 ** | |
| 764 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13) | |
| 765 ** ^^^^^^^^^^^^^^^^^^^^ | |
| 766 ** | |
| 767 ** This routine analyzes terms such as the middle term in the above example. | |
| 768 ** A WhereOrTerm object is computed and attached to the term under | |
| 769 ** analysis, regardless of the outcome of the analysis. Hence: | |
| 770 ** | |
| 771 ** WhereTerm.wtFlags |= TERM_ORINFO | |
| 772 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object | |
| 773 ** | |
| 774 ** The term being analyzed must have two or more of OR-connected subterms. | |
| 775 ** A single subterm might be a set of AND-connected sub-subterms. | |
| 776 ** Examples of terms under analysis: | |
| 777 ** | |
| 778 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5 | |
| 779 ** (B) x=expr1 OR expr2=x OR x=expr3 | |
| 780 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15) | |
| 781 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*') | |
| 782 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6) | |
| 783 ** | |
| 784 ** CASE 1: | |
| 785 ** | |
| 786 ** If all subterms are of the form T.C=expr for some single column of C and | |
| 787 ** a single table T (as shown in example B above) then create a new virtual | |
| 788 ** term that is an equivalent IN expression. In other words, if the term | |
| 789 ** being analyzed is: | |
| 790 ** | |
| 791 ** x = expr1 OR expr2 = x OR x = expr3 | |
| 792 ** | |
| 793 ** then create a new virtual term like this: | |
| 794 ** | |
| 795 ** x IN (expr1,expr2,expr3) | |
| 796 ** | |
| 797 ** CASE 2: | |
| 798 ** | |
| 799 ** If all subterms are indexable by a single table T, then set | |
| 800 ** | |
| 801 ** WhereTerm.eOperator = WO_OR | |
| 802 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T | |
| 803 ** | |
| 804 ** A subterm is "indexable" if it is of the form | |
| 805 ** "T.C <op> <expr>" where C is any column of table T and | |
| 806 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN". | |
| 807 ** A subterm is also indexable if it is an AND of two or more | |
| 808 ** subsubterms at least one of which is indexable. Indexable AND | |
| 809 ** subterms have their eOperator set to WO_AND and they have | |
| 810 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object. | |
| 811 ** | |
| 812 ** From another point of view, "indexable" means that the subterm could | |
| 813 ** potentially be used with an index if an appropriate index exists. | |
| 814 ** This analysis does not consider whether or not the index exists; that | |
| 815 ** is decided elsewhere. This analysis only looks at whether subterms | |
| 816 ** appropriate for indexing exist. | |
| 817 ** | |
| 818 ** All examples A through E above satisfy case 2. But if a term | |
| 819 ** also satisfies case 1 (such as B) we know that the optimizer will | |
| 820 ** always prefer case 1, so in that case we pretend that case 2 is not | |
| 821 ** satisfied. | |
| 822 ** | |
| 823 ** It might be the case that multiple tables are indexable. For example, | |
| 824 ** (E) above is indexable on tables P, Q, and R. | |
| 825 ** | |
| 826 ** Terms that satisfy case 2 are candidates for lookup by using | |
| 827 ** separate indices to find rowids for each subterm and composing | |
| 828 ** the union of all rowids using a RowSet object. This is similar | |
| 829 ** to "bitmap indices" in other database engines. | |
| 830 ** | |
| 831 ** OTHERWISE: | |
| 832 ** | |
| 833 ** If neither case 1 nor case 2 apply, then leave the eOperator set to | |
| 834 ** zero. This term is not useful for search. | |
| 835 */ | |
| 836 static void exprAnalyzeOrTerm( | |
| 837 SrcList *pSrc, /* the FROM clause */ | |
| 838 WhereClause *pWC, /* the complete WHERE clause */ | |
| 839 int idxTerm /* Index of the OR-term to be analyzed */ | |
| 840 ){ | |
| 841 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ | |
| 842 Parse *pParse = pWInfo->pParse; /* Parser context */ | |
| 843 sqlite3 *db = pParse->db; /* Database connection */ | |
| 844 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */ | |
| 845 Expr *pExpr = pTerm->pExpr; /* The expression of the term */ | |
| 846 int i; /* Loop counters */ | |
| 847 WhereClause *pOrWc; /* Breakup of pTerm into subterms */ | |
| 848 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */ | |
| 849 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */ | |
| 850 Bitmask chngToIN; /* Tables that might satisfy case 1 */ | |
| 851 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */ | |
| 852 | |
| 853 /* | |
| 854 ** Break the OR clause into its separate subterms. The subterms are | |
| 855 ** stored in a WhereClause structure containing within the WhereOrInfo | |
| 856 ** object that is attached to the original OR clause term. | |
| 857 */ | |
| 858 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 ); | |
| 859 assert( pExpr->op==TK_OR ); | |
| 860 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo)); | |
| 861 if( pOrInfo==0 ) return; | |
| 862 pTerm->wtFlags |= TERM_ORINFO; | |
| 863 pOrWc = &pOrInfo->wc; | |
| 864 whereClauseInit(pOrWc, pWInfo); | |
| 865 whereSplit(pOrWc, pExpr, TK_OR); | |
| 866 exprAnalyzeAll(pSrc, pOrWc); | |
| 867 if( db->mallocFailed ) return; | |
| 868 assert( pOrWc->nTerm>=2 ); | |
| 869 | |
| 870 /* | |
| 871 ** Compute the set of tables that might satisfy cases 1 or 2. | |
| 872 */ | |
| 873 indexable = ~(Bitmask)0; | |
| 874 chngToIN = ~(Bitmask)0; | |
| 875 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){ | |
| 876 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){ | |
| 877 WhereAndInfo *pAndInfo; | |
| 878 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 ); | |
| 879 chngToIN = 0; | |
| 880 pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo)); | |
| 881 if( pAndInfo ){ | |
| 882 WhereClause *pAndWC; | |
| 883 WhereTerm *pAndTerm; | |
| 884 int j; | |
| 885 Bitmask b = 0; | |
| 886 pOrTerm->u.pAndInfo = pAndInfo; | |
| 887 pOrTerm->wtFlags |= TERM_ANDINFO; | |
| 888 pOrTerm->eOperator = WO_AND; | |
| 889 pAndWC = &pAndInfo->wc; | |
| 890 whereClauseInit(pAndWC, pWC->pWInfo); | |
| 891 whereSplit(pAndWC, pOrTerm->pExpr, TK_AND); | |
| 892 exprAnalyzeAll(pSrc, pAndWC); | |
| 893 pAndWC->pOuter = pWC; | |
| 894 testcase( db->mallocFailed ); | |
| 895 if( !db->mallocFailed ){ | |
| 896 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){ | |
| 897 assert( pAndTerm->pExpr ); | |
| 898 if( allowedOp(pAndTerm->pExpr->op) ){ | |
| 899 b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor); | |
| 900 } | |
| 901 } | |
| 902 } | |
| 903 indexable &= b; | |
| 904 } | |
| 905 }else if( pOrTerm->wtFlags & TERM_COPIED ){ | |
| 906 /* Skip this term for now. We revisit it when we process the | |
| 907 ** corresponding TERM_VIRTUAL term */ | |
| 908 }else{ | |
| 909 Bitmask b; | |
| 910 b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor); | |
| 911 if( pOrTerm->wtFlags & TERM_VIRTUAL ){ | |
| 912 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent]; | |
| 913 b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor); | |
| 914 } | |
| 915 indexable &= b; | |
| 916 if( (pOrTerm->eOperator & WO_EQ)==0 ){ | |
| 917 chngToIN = 0; | |
| 918 }else{ | |
| 919 chngToIN &= b; | |
| 920 } | |
| 921 } | |
| 922 } | |
| 923 | |
| 924 /* | |
| 925 ** Record the set of tables that satisfy case 2. The set might be | |
| 926 ** empty. | |
| 927 */ | |
| 928 pOrInfo->indexable = indexable; | |
| 929 pTerm->eOperator = indexable==0 ? 0 : WO_OR; | |
| 930 | |
| 931 /* | |
| 932 ** chngToIN holds a set of tables that *might* satisfy case 1. But | |
| 933 ** we have to do some additional checking to see if case 1 really | |
| 934 ** is satisfied. | |
| 935 ** | |
| 936 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means | |
| 937 ** that there is no possibility of transforming the OR clause into an | |
| 938 ** IN operator because one or more terms in the OR clause contain | |
| 939 ** something other than == on a column in the single table. The 1-bit | |
| 940 ** case means that every term of the OR clause is of the form | |
| 941 ** "table.column=expr" for some single table. The one bit that is set | |
| 942 ** will correspond to the common table. We still need to check to make | |
| 943 ** sure the same column is used on all terms. The 2-bit case is when | |
| 944 ** the all terms are of the form "table1.column=table2.column". It | |
| 945 ** might be possible to form an IN operator with either table1.column | |
| 946 ** or table2.column as the LHS if either is common to every term of | |
| 947 ** the OR clause. | |
| 948 ** | |
| 949 ** Note that terms of the form "table.column1=table.column2" (the | |
| 950 ** same table on both sizes of the ==) cannot be optimized. | |
| 951 */ | |
| 952 if( chngToIN ){ | |
| 953 int okToChngToIN = 0; /* True if the conversion to IN is valid */ | |
| 954 int iColumn = -1; /* Column index on lhs of IN operator */ | |
| 955 int iCursor = -1; /* Table cursor common to all terms */ | |
| 956 int j = 0; /* Loop counter */ | |
| 957 | |
| 958 /* Search for a table and column that appears on one side or the | |
| 959 ** other of the == operator in every subterm. That table and column | |
| 960 ** will be recorded in iCursor and iColumn. There might not be any | |
| 961 ** such table and column. Set okToChngToIN if an appropriate table | |
| 962 ** and column is found but leave okToChngToIN false if not found. | |
| 963 */ | |
| 964 for(j=0; j<2 && !okToChngToIN; j++){ | |
| 965 pOrTerm = pOrWc->a; | |
| 966 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){ | |
| 967 assert( pOrTerm->eOperator & WO_EQ ); | |
| 968 pOrTerm->wtFlags &= ~TERM_OR_OK; | |
| 969 if( pOrTerm->leftCursor==iCursor ){ | |
| 970 /* This is the 2-bit case and we are on the second iteration and | |
| 971 ** current term is from the first iteration. So skip this term. */ | |
| 972 assert( j==1 ); | |
| 973 continue; | |
| 974 } | |
| 975 if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){ | |
| 976 /* This term must be of the form t1.a==t2.b where t2 is in the | |
| 977 ** chngToIN set but t1 is not. This term will be either preceded | |
| 978 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term | |
| 979 ** and use its inversion. */ | |
| 980 testcase( pOrTerm->wtFlags & TERM_COPIED ); | |
| 981 testcase( pOrTerm->wtFlags & TERM_VIRTUAL ); | |
| 982 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) ); | |
| 983 continue; | |
| 984 } | |
| 985 iColumn = pOrTerm->u.leftColumn; | |
| 986 iCursor = pOrTerm->leftCursor; | |
| 987 break; | |
| 988 } | |
| 989 if( i<0 ){ | |
| 990 /* No candidate table+column was found. This can only occur | |
| 991 ** on the second iteration */ | |
| 992 assert( j==1 ); | |
| 993 assert( IsPowerOfTwo(chngToIN) ); | |
| 994 assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) ); | |
| 995 break; | |
| 996 } | |
| 997 testcase( j==1 ); | |
| 998 | |
| 999 /* We have found a candidate table and column. Check to see if that | |
| 1000 ** table and column is common to every term in the OR clause */ | |
| 1001 okToChngToIN = 1; | |
| 1002 for(; i>=0 && okToChngToIN; i--, pOrTerm++){ | |
| 1003 assert( pOrTerm->eOperator & WO_EQ ); | |
| 1004 if( pOrTerm->leftCursor!=iCursor ){ | |
| 1005 pOrTerm->wtFlags &= ~TERM_OR_OK; | |
| 1006 }else if( pOrTerm->u.leftColumn!=iColumn ){ | |
| 1007 okToChngToIN = 0; | |
| 1008 }else{ | |
| 1009 int affLeft, affRight; | |
| 1010 /* If the right-hand side is also a column, then the affinities | |
| 1011 ** of both right and left sides must be such that no type | |
| 1012 ** conversions are required on the right. (Ticket #2249) | |
| 1013 */ | |
| 1014 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight); | |
| 1015 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft); | |
| 1016 if( affRight!=0 && affRight!=affLeft ){ | |
| 1017 okToChngToIN = 0; | |
| 1018 }else{ | |
| 1019 pOrTerm->wtFlags |= TERM_OR_OK; | |
| 1020 } | |
| 1021 } | |
| 1022 } | |
| 1023 } | |
| 1024 | |
| 1025 /* At this point, okToChngToIN is true if original pTerm satisfies | |
| 1026 ** case 1. In that case, construct a new virtual term that is | |
| 1027 ** pTerm converted into an IN operator. | |
| 1028 */ | |
| 1029 if( okToChngToIN ){ | |
| 1030 Expr *pDup; /* A transient duplicate expression */ | |
| 1031 ExprList *pList = 0; /* The RHS of the IN operator */ | |
| 1032 Expr *pLeft = 0; /* The LHS of the IN operator */ | |
| 1033 Expr *pNew; /* The complete IN operator */ | |
| 1034 | |
| 1035 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){ | |
| 1036 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue; | |
| 1037 assert( pOrTerm->eOperator & WO_EQ ); | |
| 1038 assert( pOrTerm->leftCursor==iCursor ); | |
| 1039 assert( pOrTerm->u.leftColumn==iColumn ); | |
| 1040 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0); | |
| 1041 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup); | |
| 1042 pLeft = pOrTerm->pExpr->pLeft; | |
| 1043 } | |
| 1044 assert( pLeft!=0 ); | |
| 1045 pDup = sqlite3ExprDup(db, pLeft, 0); | |
| 1046 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0); | |
| 1047 if( pNew ){ | |
| 1048 int idxNew; | |
| 1049 transferJoinMarkings(pNew, pExpr); | |
| 1050 assert( !ExprHasProperty(pNew, EP_xIsSelect) ); | |
| 1051 pNew->x.pList = pList; | |
| 1052 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC); | |
| 1053 testcase( idxNew==0 ); | |
| 1054 exprAnalyze(pSrc, pWC, idxNew); | |
| 1055 pTerm = &pWC->a[idxTerm]; | |
| 1056 pWC->a[idxNew].iParent = idxTerm; | |
| 1057 pTerm->nChild = 1; | |
| 1058 }else{ | |
| 1059 sqlite3ExprListDelete(db, pList); | |
| 1060 } | |
| 1061 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */ | |
| 1062 } | |
| 1063 } | |
| 1064 } | |
| 1065 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */ | |
| 1066 | |
| 1067 /* | |
| 1068 ** The input to this routine is an WhereTerm structure with only the | |
| 1069 ** "pExpr" field filled in. The job of this routine is to analyze the | |
| 1070 ** subexpression and populate all the other fields of the WhereTerm | |
| 1071 ** structure. | |
| 1072 ** | |
| 1073 ** If the expression is of the form "<expr> <op> X" it gets commuted | |
| 1074 ** to the standard form of "X <op> <expr>". | |
| 1075 ** | |
| 1076 ** If the expression is of the form "X <op> Y" where both X and Y are | |
| 1077 ** columns, then the original expression is unchanged and a new virtual | |
| 1078 ** term of the form "Y <op> X" is added to the WHERE clause and | |
| 1079 ** analyzed separately. The original term is marked with TERM_COPIED | |
| 1080 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr | |
| 1081 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it | |
| 1082 ** is a commuted copy of a prior term.) The original term has nChild=1 | |
| 1083 ** and the copy has idxParent set to the index of the original term. | |
| 1084 */ | |
| 1085 static void exprAnalyze( | |
| 1086 SrcList *pSrc, /* the FROM clause */ | |
| 1087 WhereClause *pWC, /* the WHERE clause */ | |
| 1088 int idxTerm /* Index of the term to be analyzed */ | |
| 1089 ){ | |
| 1090 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */ | |
| 1091 WhereTerm *pTerm; /* The term to be analyzed */ | |
| 1092 WhereMaskSet *pMaskSet; /* Set of table index masks */ | |
| 1093 Expr *pExpr; /* The expression to be analyzed */ | |
| 1094 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */ | |
| 1095 Bitmask prereqAll; /* Prerequesites of pExpr */ | |
| 1096 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */ | |
| 1097 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */ | |
| 1098 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */ | |
| 1099 int noCase = 0; /* LIKE/GLOB distinguishes case */ | |
| 1100 int op; /* Top-level operator. pExpr->op */ | |
| 1101 Parse *pParse = pWInfo->pParse; /* Parsing context */ | |
| 1102 sqlite3 *db = pParse->db; /* Database connection */ | |
| 1103 | |
| 1104 if( db->mallocFailed ){ | |
| 1105 return; | |
| 1106 } | |
| 1107 pTerm = &pWC->a[idxTerm]; | |
| 1108 pMaskSet = &pWInfo->sMaskSet; | |
| 1109 pExpr = pTerm->pExpr; | |
| 1110 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE ); | |
| 1111 prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft); | |
| 1112 op = pExpr->op; | |
| 1113 if( op==TK_IN ){ | |
| 1114 assert( pExpr->pRight==0 ); | |
| 1115 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ | |
| 1116 pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect); | |
| 1117 }else{ | |
| 1118 pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList); | |
| 1119 } | |
| 1120 }else if( op==TK_ISNULL ){ | |
| 1121 pTerm->prereqRight = 0; | |
| 1122 }else{ | |
| 1123 pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight); | |
| 1124 } | |
| 1125 prereqAll = exprTableUsage(pMaskSet, pExpr); | |
| 1126 if( ExprHasProperty(pExpr, EP_FromJoin) ){ | |
| 1127 Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable); | |
| 1128 prereqAll |= x; | |
| 1129 extraRight = x-1; /* ON clause terms may not be used with an index | |
| 1130 ** on left table of a LEFT JOIN. Ticket #3015 */ | |
| 1131 } | |
| 1132 pTerm->prereqAll = prereqAll; | |
| 1133 pTerm->leftCursor = -1; | |
| 1134 pTerm->iParent = -1; | |
| 1135 pTerm->eOperator = 0; | |
| 1136 if( allowedOp(op) ){ | |
| 1137 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft); | |
| 1138 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight); | |
| 1139 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV; | |
| 1140 if( pLeft->op==TK_COLUMN ){ | |
| 1141 pTerm->leftCursor = pLeft->iTable; | |
| 1142 pTerm->u.leftColumn = pLeft->iColumn; | |
| 1143 pTerm->eOperator = operatorMask(op) & opMask; | |
| 1144 } | |
| 1145 if( pRight && pRight->op==TK_COLUMN ){ | |
| 1146 WhereTerm *pNew; | |
| 1147 Expr *pDup; | |
| 1148 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */ | |
| 1149 if( pTerm->leftCursor>=0 ){ | |
| 1150 int idxNew; | |
| 1151 pDup = sqlite3ExprDup(db, pExpr, 0); | |
| 1152 if( db->mallocFailed ){ | |
| 1153 sqlite3ExprDelete(db, pDup); | |
| 1154 return; | |
| 1155 } | |
| 1156 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC); | |
| 1157 if( idxNew==0 ) return; | |
| 1158 pNew = &pWC->a[idxNew]; | |
| 1159 pNew->iParent = idxTerm; | |
| 1160 pTerm = &pWC->a[idxTerm]; | |
| 1161 pTerm->nChild = 1; | |
| 1162 pTerm->wtFlags |= TERM_COPIED; | |
| 1163 if( pExpr->op==TK_EQ | |
| 1164 && !ExprHasProperty(pExpr, EP_FromJoin) | |
| 1165 && OptimizationEnabled(db, SQLITE_Transitive) | |
| 1166 ){ | |
| 1167 pTerm->eOperator |= WO_EQUIV; | |
| 1168 eExtraOp = WO_EQUIV; | |
| 1169 } | |
| 1170 }else{ | |
| 1171 pDup = pExpr; | |
| 1172 pNew = pTerm; | |
| 1173 } | |
| 1174 exprCommute(pParse, pDup); | |
| 1175 pLeft = sqlite3ExprSkipCollate(pDup->pLeft); | |
| 1176 pNew->leftCursor = pLeft->iTable; | |
| 1177 pNew->u.leftColumn = pLeft->iColumn; | |
| 1178 testcase( (prereqLeft | extraRight) != prereqLeft ); | |
| 1179 pNew->prereqRight = prereqLeft | extraRight; | |
| 1180 pNew->prereqAll = prereqAll; | |
| 1181 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask; | |
| 1182 } | |
| 1183 } | |
| 1184 | |
| 1185 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION | |
| 1186 /* If a term is the BETWEEN operator, create two new virtual terms | |
| 1187 ** that define the range that the BETWEEN implements. For example: | |
| 1188 ** | |
| 1189 ** a BETWEEN b AND c | |
| 1190 ** | |
| 1191 ** is converted into: | |
| 1192 ** | |
| 1193 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c) | |
| 1194 ** | |
| 1195 ** The two new terms are added onto the end of the WhereClause object. | |
| 1196 ** The new terms are "dynamic" and are children of the original BETWEEN | |
| 1197 ** term. That means that if the BETWEEN term is coded, the children are | |
| 1198 ** skipped. Or, if the children are satisfied by an index, the original | |
| 1199 ** BETWEEN term is skipped. | |
| 1200 */ | |
| 1201 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){ | |
| 1202 ExprList *pList = pExpr->x.pList; | |
| 1203 int i; | |
| 1204 static const u8 ops[] = {TK_GE, TK_LE}; | |
| 1205 assert( pList!=0 ); | |
| 1206 assert( pList->nExpr==2 ); | |
| 1207 for(i=0; i<2; i++){ | |
| 1208 Expr *pNewExpr; | |
| 1209 int idxNew; | |
| 1210 pNewExpr = sqlite3PExpr(pParse, ops[i], | |
| 1211 sqlite3ExprDup(db, pExpr->pLeft, 0), | |
| 1212 sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0); | |
| 1213 transferJoinMarkings(pNewExpr, pExpr); | |
| 1214 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); | |
| 1215 testcase( idxNew==0 ); | |
| 1216 exprAnalyze(pSrc, pWC, idxNew); | |
| 1217 pTerm = &pWC->a[idxTerm]; | |
| 1218 pWC->a[idxNew].iParent = idxTerm; | |
| 1219 } | |
| 1220 pTerm->nChild = 2; | |
| 1221 } | |
| 1222 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */ | |
| 1223 | |
| 1224 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY) | |
| 1225 /* Analyze a term that is composed of two or more subterms connected by | |
| 1226 ** an OR operator. | |
| 1227 */ | |
| 1228 else if( pExpr->op==TK_OR ){ | |
| 1229 assert( pWC->op==TK_AND ); | |
| 1230 exprAnalyzeOrTerm(pSrc, pWC, idxTerm); | |
| 1231 pTerm = &pWC->a[idxTerm]; | |
| 1232 } | |
| 1233 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ | |
| 1234 | |
| 1235 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION | |
| 1236 /* Add constraints to reduce the search space on a LIKE or GLOB | |
| 1237 ** operator. | |
| 1238 ** | |
| 1239 ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints | |
| 1240 ** | |
| 1241 ** x>='abc' AND x<'abd' AND x LIKE 'abc%' | |
| 1242 ** | |
| 1243 ** The last character of the prefix "abc" is incremented to form the | |
| 1244 ** termination condition "abd". | |
| 1245 */ | |
| 1246 if( pWC->op==TK_AND | |
| 1247 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase) | |
| 1248 ){ | |
| 1249 Expr *pLeft; /* LHS of LIKE/GLOB operator */ | |
| 1250 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */ | |
| 1251 Expr *pNewExpr1; | |
| 1252 Expr *pNewExpr2; | |
| 1253 int idxNew1; | |
| 1254 int idxNew2; | |
| 1255 const char *zCollSeqName; /* Name of collating sequence */ | |
| 1256 | |
| 1257 pLeft = pExpr->x.pList->a[1].pExpr; | |
| 1258 pStr2 = sqlite3ExprDup(db, pStr1, 0); | |
| 1259 if( !db->mallocFailed ){ | |
| 1260 u8 c, *pC; /* Last character before the first wildcard */ | |
| 1261 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1]; | |
| 1262 c = *pC; | |
| 1263 if( noCase ){ | |
| 1264 /* The point is to increment the last character before the first | |
| 1265 ** wildcard. But if we increment '@', that will push it into the | |
| 1266 ** alphabetic range where case conversions will mess up the | |
| 1267 ** inequality. To avoid this, make sure to also run the full | |
| 1268 ** LIKE on all candidate expressions by clearing the isComplete flag | |
| 1269 */ | |
| 1270 if( c=='A'-1 ) isComplete = 0; | |
| 1271 c = sqlite3UpperToLower[c]; | |
| 1272 } | |
| 1273 *pC = c + 1; | |
| 1274 } | |
| 1275 zCollSeqName = noCase ? "NOCASE" : "BINARY"; | |
| 1276 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0); | |
| 1277 pNewExpr1 = sqlite3PExpr(pParse, TK_GE, | |
| 1278 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName), | |
| 1279 pStr1, 0); | |
| 1280 transferJoinMarkings(pNewExpr1, pExpr); | |
| 1281 idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC); | |
| 1282 testcase( idxNew1==0 ); | |
| 1283 exprAnalyze(pSrc, pWC, idxNew1); | |
| 1284 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0); | |
| 1285 pNewExpr2 = sqlite3PExpr(pParse, TK_LT, | |
| 1286 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName), | |
| 1287 pStr2, 0); | |
| 1288 transferJoinMarkings(pNewExpr2, pExpr); | |
| 1289 idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC); | |
| 1290 testcase( idxNew2==0 ); | |
| 1291 exprAnalyze(pSrc, pWC, idxNew2); | |
| 1292 pTerm = &pWC->a[idxTerm]; | |
| 1293 if( isComplete ){ | |
| 1294 pWC->a[idxNew1].iParent = idxTerm; | |
| 1295 pWC->a[idxNew2].iParent = idxTerm; | |
| 1296 pTerm->nChild = 2; | |
| 1297 } | |
| 1298 } | |
| 1299 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */ | |
| 1300 | |
| 1301 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 1302 /* Add a WO_MATCH auxiliary term to the constraint set if the | |
| 1303 ** current expression is of the form: column MATCH expr. | |
| 1304 ** This information is used by the xBestIndex methods of | |
| 1305 ** virtual tables. The native query optimizer does not attempt | |
| 1306 ** to do anything with MATCH functions. | |
| 1307 */ | |
| 1308 if( isMatchOfColumn(pExpr) ){ | |
| 1309 int idxNew; | |
| 1310 Expr *pRight, *pLeft; | |
| 1311 WhereTerm *pNewTerm; | |
| 1312 Bitmask prereqColumn, prereqExpr; | |
| 1313 | |
| 1314 pRight = pExpr->x.pList->a[0].pExpr; | |
| 1315 pLeft = pExpr->x.pList->a[1].pExpr; | |
| 1316 prereqExpr = exprTableUsage(pMaskSet, pRight); | |
| 1317 prereqColumn = exprTableUsage(pMaskSet, pLeft); | |
| 1318 if( (prereqExpr & prereqColumn)==0 ){ | |
| 1319 Expr *pNewExpr; | |
| 1320 pNewExpr = sqlite3PExpr(pParse, TK_MATCH, | |
| 1321 0, sqlite3ExprDup(db, pRight, 0), 0); | |
| 1322 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC); | |
| 1323 testcase( idxNew==0 ); | |
| 1324 pNewTerm = &pWC->a[idxNew]; | |
| 1325 pNewTerm->prereqRight = prereqExpr; | |
| 1326 pNewTerm->leftCursor = pLeft->iTable; | |
| 1327 pNewTerm->u.leftColumn = pLeft->iColumn; | |
| 1328 pNewTerm->eOperator = WO_MATCH; | |
| 1329 pNewTerm->iParent = idxTerm; | |
| 1330 pTerm = &pWC->a[idxTerm]; | |
| 1331 pTerm->nChild = 1; | |
| 1332 pTerm->wtFlags |= TERM_COPIED; | |
| 1333 pNewTerm->prereqAll = pTerm->prereqAll; | |
| 1334 } | |
| 1335 } | |
| 1336 #endif /* SQLITE_OMIT_VIRTUALTABLE */ | |
| 1337 | |
| 1338 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | |
| 1339 /* When sqlite_stat3 histogram data is available an operator of the | |
| 1340 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently | |
| 1341 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a | |
| 1342 ** virtual term of that form. | |
| 1343 ** | |
| 1344 ** Note that the virtual term must be tagged with TERM_VNULL. This | |
| 1345 ** TERM_VNULL tag will suppress the not-null check at the beginning | |
| 1346 ** of the loop. Without the TERM_VNULL flag, the not-null check at | |
| 1347 ** the start of the loop will prevent any results from being returned. | |
| 1348 */ | |
| 1349 if( pExpr->op==TK_NOTNULL | |
| 1350 && pExpr->pLeft->op==TK_COLUMN | |
| 1351 && pExpr->pLeft->iColumn>=0 | |
| 1352 && OptimizationEnabled(db, SQLITE_Stat3) | |
| 1353 ){ | |
| 1354 Expr *pNewExpr; | |
| 1355 Expr *pLeft = pExpr->pLeft; | |
| 1356 int idxNew; | |
| 1357 WhereTerm *pNewTerm; | |
| 1358 | |
| 1359 pNewExpr = sqlite3PExpr(pParse, TK_GT, | |
| 1360 sqlite3ExprDup(db, pLeft, 0), | |
| 1361 sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0); | |
| 1362 | |
| 1363 idxNew = whereClauseInsert(pWC, pNewExpr, | |
| 1364 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL); | |
| 1365 if( idxNew ){ | |
| 1366 pNewTerm = &pWC->a[idxNew]; | |
| 1367 pNewTerm->prereqRight = 0; | |
| 1368 pNewTerm->leftCursor = pLeft->iTable; | |
| 1369 pNewTerm->u.leftColumn = pLeft->iColumn; | |
| 1370 pNewTerm->eOperator = WO_GT; | |
| 1371 pNewTerm->iParent = idxTerm; | |
| 1372 pTerm = &pWC->a[idxTerm]; | |
| 1373 pTerm->nChild = 1; | |
| 1374 pTerm->wtFlags |= TERM_COPIED; | |
| 1375 pNewTerm->prereqAll = pTerm->prereqAll; | |
| 1376 } | |
| 1377 } | |
| 1378 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ | |
| 1379 | |
| 1380 /* Prevent ON clause terms of a LEFT JOIN from being used to drive | |
| 1381 ** an index for tables to the left of the join. | |
| 1382 */ | |
| 1383 pTerm->prereqRight |= extraRight; | |
| 1384 } | |
| 1385 | |
| 1386 /* | 360 /* |
| 1387 ** This function searches pList for an entry that matches the iCol-th column | 361 ** This function searches pList for an entry that matches the iCol-th column |
| 1388 ** of index pIdx. | 362 ** of index pIdx. |
| 1389 ** | 363 ** |
| 1390 ** If such an expression is found, its index in pList->a[] is returned. If | 364 ** If such an expression is found, its index in pList->a[] is returned. If |
| 1391 ** no expression is found, -1 is returned. | 365 ** no expression is found, -1 is returned. |
| 1392 */ | 366 */ |
| 1393 static int findIndexCol( | 367 static int findIndexCol( |
| 1394 Parse *pParse, /* Parse context */ | 368 Parse *pParse, /* Parse context */ |
| 1395 ExprList *pList, /* Expression list to search */ | 369 ExprList *pList, /* Expression list to search */ |
| 1396 int iBase, /* Cursor for table associated with pIdx */ | 370 int iBase, /* Cursor for table associated with pIdx */ |
| 1397 Index *pIdx, /* Index to match column of */ | 371 Index *pIdx, /* Index to match column of */ |
| 1398 int iCol /* Column of index to match */ | 372 int iCol /* Column of index to match */ |
| 1399 ){ | 373 ){ |
| 1400 int i; | 374 int i; |
| 1401 const char *zColl = pIdx->azColl[iCol]; | 375 const char *zColl = pIdx->azColl[iCol]; |
| 1402 | 376 |
| 1403 for(i=0; i<pList->nExpr; i++){ | 377 for(i=0; i<pList->nExpr; i++){ |
| 1404 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr); | 378 Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr); |
| 1405 if( p->op==TK_COLUMN | 379 if( p->op==TK_COLUMN |
| 1406 && p->iColumn==pIdx->aiColumn[iCol] | 380 && p->iColumn==pIdx->aiColumn[iCol] |
| 1407 && p->iTable==iBase | 381 && p->iTable==iBase |
| 1408 ){ | 382 ){ |
| 1409 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); | 383 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); |
| 1410 if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){ | 384 if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){ |
| 1411 return i; | 385 return i; |
| 1412 } | 386 } |
| 1413 } | 387 } |
| 1414 } | 388 } |
| 1415 | 389 |
| 1416 return -1; | 390 return -1; |
| 1417 } | 391 } |
| 1418 | 392 |
| 1419 /* | 393 /* |
| 394 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL |
| 395 */ |
| 396 static int indexColumnNotNull(Index *pIdx, int iCol){ |
| 397 int j; |
| 398 assert( pIdx!=0 ); |
| 399 assert( iCol>=0 && iCol<pIdx->nColumn ); |
| 400 j = pIdx->aiColumn[iCol]; |
| 401 if( j>=0 ){ |
| 402 return pIdx->pTable->aCol[j].notNull; |
| 403 }else if( j==(-1) ){ |
| 404 return 1; |
| 405 }else{ |
| 406 assert( j==(-2) ); |
| 407 return 0; /* Assume an indexed expression can always yield a NULL */ |
| 408 |
| 409 } |
| 410 } |
| 411 |
| 412 /* |
| 1420 ** Return true if the DISTINCT expression-list passed as the third argument | 413 ** Return true if the DISTINCT expression-list passed as the third argument |
| 1421 ** is redundant. | 414 ** is redundant. |
| 1422 ** | 415 ** |
| 1423 ** A DISTINCT list is redundant if the database contains some subset of | 416 ** A DISTINCT list is redundant if any subset of the columns in the |
| 1424 ** columns that are unique and non-null. | 417 ** DISTINCT list are collectively unique and individually non-null. |
| 1425 */ | 418 */ |
| 1426 static int isDistinctRedundant( | 419 static int isDistinctRedundant( |
| 1427 Parse *pParse, /* Parsing context */ | 420 Parse *pParse, /* Parsing context */ |
| 1428 SrcList *pTabList, /* The FROM clause */ | 421 SrcList *pTabList, /* The FROM clause */ |
| 1429 WhereClause *pWC, /* The WHERE clause */ | 422 WhereClause *pWC, /* The WHERE clause */ |
| 1430 ExprList *pDistinct /* The result set that needs to be DISTINCT */ | 423 ExprList *pDistinct /* The result set that needs to be DISTINCT */ |
| 1431 ){ | 424 ){ |
| 1432 Table *pTab; | 425 Table *pTab; |
| 1433 Index *pIdx; | 426 Index *pIdx; |
| 1434 int i; | 427 int i; |
| (...skipping 24 matching lines...) Expand all Loading... |
| 1459 ** list, or else the WHERE clause contains a term of the form "col=X", | 452 ** list, or else the WHERE clause contains a term of the form "col=X", |
| 1460 ** where X is a constant value. The collation sequences of the | 453 ** where X is a constant value. The collation sequences of the |
| 1461 ** comparison and select-list expressions must match those of the index. | 454 ** comparison and select-list expressions must match those of the index. |
| 1462 ** | 455 ** |
| 1463 ** 3. All of those index columns for which the WHERE clause does not | 456 ** 3. All of those index columns for which the WHERE clause does not |
| 1464 ** contain a "col=X" term are subject to a NOT NULL constraint. | 457 ** contain a "col=X" term are subject to a NOT NULL constraint. |
| 1465 */ | 458 */ |
| 1466 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ | 459 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ |
| 1467 if( !IsUniqueIndex(pIdx) ) continue; | 460 if( !IsUniqueIndex(pIdx) ) continue; |
| 1468 for(i=0; i<pIdx->nKeyCol; i++){ | 461 for(i=0; i<pIdx->nKeyCol; i++){ |
| 1469 i16 iCol = pIdx->aiColumn[i]; | 462 if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){ |
| 1470 if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){ | 463 if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break; |
| 1471 int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i); | 464 if( indexColumnNotNull(pIdx, i)==0 ) break; |
| 1472 if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){ | |
| 1473 break; | |
| 1474 } | |
| 1475 } | 465 } |
| 1476 } | 466 } |
| 1477 if( i==pIdx->nKeyCol ){ | 467 if( i==pIdx->nKeyCol ){ |
| 1478 /* This index implies that the DISTINCT qualifier is redundant. */ | 468 /* This index implies that the DISTINCT qualifier is redundant. */ |
| 1479 return 1; | 469 return 1; |
| 1480 } | 470 } |
| 1481 } | 471 } |
| 1482 | 472 |
| 1483 return 0; | 473 return 0; |
| 1484 } | 474 } |
| 1485 | 475 |
| 1486 | 476 |
| 1487 /* | 477 /* |
| 1488 ** Estimate the logarithm of the input value to base 2. | 478 ** Estimate the logarithm of the input value to base 2. |
| 1489 */ | 479 */ |
| 1490 static LogEst estLog(LogEst N){ | 480 static LogEst estLog(LogEst N){ |
| 1491 return N<=10 ? 0 : sqlite3LogEst(N) - 33; | 481 return N<=10 ? 0 : sqlite3LogEst(N) - 33; |
| 1492 } | 482 } |
| 1493 | 483 |
| 1494 /* | 484 /* |
| 485 ** Convert OP_Column opcodes to OP_Copy in previously generated code. |
| 486 ** |
| 487 ** This routine runs over generated VDBE code and translates OP_Column |
| 488 ** opcodes into OP_Copy when the table is being accessed via co-routine |
| 489 ** instead of via table lookup. |
| 490 ** |
| 491 ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on |
| 492 ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero, |
| 493 ** then each OP_Rowid is transformed into an instruction to increment the |
| 494 ** value stored in its output register. |
| 495 */ |
| 496 static void translateColumnToCopy( |
| 497 Vdbe *v, /* The VDBE containing code to translate */ |
| 498 int iStart, /* Translate from this opcode to the end */ |
| 499 int iTabCur, /* OP_Column/OP_Rowid references to this table */ |
| 500 int iRegister, /* The first column is in this register */ |
| 501 int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */ |
| 502 ){ |
| 503 VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart); |
| 504 int iEnd = sqlite3VdbeCurrentAddr(v); |
| 505 for(; iStart<iEnd; iStart++, pOp++){ |
| 506 if( pOp->p1!=iTabCur ) continue; |
| 507 if( pOp->opcode==OP_Column ){ |
| 508 pOp->opcode = OP_Copy; |
| 509 pOp->p1 = pOp->p2 + iRegister; |
| 510 pOp->p2 = pOp->p3; |
| 511 pOp->p3 = 0; |
| 512 }else if( pOp->opcode==OP_Rowid ){ |
| 513 if( bIncrRowid ){ |
| 514 /* Increment the value stored in the P2 operand of the OP_Rowid. */ |
| 515 pOp->opcode = OP_AddImm; |
| 516 pOp->p1 = pOp->p2; |
| 517 pOp->p2 = 1; |
| 518 }else{ |
| 519 pOp->opcode = OP_Null; |
| 520 pOp->p1 = 0; |
| 521 pOp->p3 = 0; |
| 522 } |
| 523 } |
| 524 } |
| 525 } |
| 526 |
| 527 /* |
| 1495 ** Two routines for printing the content of an sqlite3_index_info | 528 ** Two routines for printing the content of an sqlite3_index_info |
| 1496 ** structure. Used for testing and debugging only. If neither | 529 ** structure. Used for testing and debugging only. If neither |
| 1497 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines | 530 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines |
| 1498 ** are no-ops. | 531 ** are no-ops. |
| 1499 */ | 532 */ |
| 1500 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) | 533 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED) |
| 1501 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ | 534 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ |
| 1502 int i; | 535 int i; |
| 1503 if( !sqlite3WhereTrace ) return; | 536 if( !sqlite3WhereTrace ) return; |
| 1504 for(i=0; i<p->nConstraint; i++){ | 537 for(i=0; i<p->nConstraint; i++){ |
| (...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1542 ** could be used with an index to access pSrc, assuming an appropriate | 575 ** could be used with an index to access pSrc, assuming an appropriate |
| 1543 ** index existed. | 576 ** index existed. |
| 1544 */ | 577 */ |
| 1545 static int termCanDriveIndex( | 578 static int termCanDriveIndex( |
| 1546 WhereTerm *pTerm, /* WHERE clause term to check */ | 579 WhereTerm *pTerm, /* WHERE clause term to check */ |
| 1547 struct SrcList_item *pSrc, /* Table we are trying to access */ | 580 struct SrcList_item *pSrc, /* Table we are trying to access */ |
| 1548 Bitmask notReady /* Tables in outer loops of the join */ | 581 Bitmask notReady /* Tables in outer loops of the join */ |
| 1549 ){ | 582 ){ |
| 1550 char aff; | 583 char aff; |
| 1551 if( pTerm->leftCursor!=pSrc->iCursor ) return 0; | 584 if( pTerm->leftCursor!=pSrc->iCursor ) return 0; |
| 1552 if( (pTerm->eOperator & WO_EQ)==0 ) return 0; | 585 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0; |
| 1553 if( (pTerm->prereqRight & notReady)!=0 ) return 0; | 586 if( (pTerm->prereqRight & notReady)!=0 ) return 0; |
| 1554 if( pTerm->u.leftColumn<0 ) return 0; | 587 if( pTerm->u.leftColumn<0 ) return 0; |
| 1555 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; | 588 aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity; |
| 1556 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; | 589 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0; |
| 590 testcase( pTerm->pExpr->op==TK_IS ); |
| 1557 return 1; | 591 return 1; |
| 1558 } | 592 } |
| 1559 #endif | 593 #endif |
| 1560 | 594 |
| 1561 | 595 |
| 1562 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX | 596 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX |
| 1563 /* | 597 /* |
| 1564 ** Generate code to construct the Index object for an automatic index | 598 ** Generate code to construct the Index object for an automatic index |
| 1565 ** and to set up the WhereLevel object pLevel so that the code generator | 599 ** and to set up the WhereLevel object pLevel so that the code generator |
| 1566 ** makes use of the automatic index. | 600 ** makes use of the automatic index. |
| (...skipping 16 matching lines...) Expand all Loading... |
| 1583 int regRecord; /* Register holding an index record */ | 617 int regRecord; /* Register holding an index record */ |
| 1584 int n; /* Column counter */ | 618 int n; /* Column counter */ |
| 1585 int i; /* Loop counter */ | 619 int i; /* Loop counter */ |
| 1586 int mxBitCol; /* Maximum column in pSrc->colUsed */ | 620 int mxBitCol; /* Maximum column in pSrc->colUsed */ |
| 1587 CollSeq *pColl; /* Collating sequence to on a column */ | 621 CollSeq *pColl; /* Collating sequence to on a column */ |
| 1588 WhereLoop *pLoop; /* The Loop object */ | 622 WhereLoop *pLoop; /* The Loop object */ |
| 1589 char *zNotUsed; /* Extra space on the end of pIdx */ | 623 char *zNotUsed; /* Extra space on the end of pIdx */ |
| 1590 Bitmask idxCols; /* Bitmap of columns used for indexing */ | 624 Bitmask idxCols; /* Bitmap of columns used for indexing */ |
| 1591 Bitmask extraCols; /* Bitmap of additional columns */ | 625 Bitmask extraCols; /* Bitmap of additional columns */ |
| 1592 u8 sentWarning = 0; /* True if a warnning has been issued */ | 626 u8 sentWarning = 0; /* True if a warnning has been issued */ |
| 627 Expr *pPartial = 0; /* Partial Index Expression */ |
| 628 int iContinue = 0; /* Jump here to skip excluded rows */ |
| 629 struct SrcList_item *pTabItem; /* FROM clause term being indexed */ |
| 630 int addrCounter = 0; /* Address where integer counter is initialized */ |
| 631 int regBase; /* Array of registers where record is assembled */ |
| 1593 | 632 |
| 1594 /* Generate code to skip over the creation and initialization of the | 633 /* Generate code to skip over the creation and initialization of the |
| 1595 ** transient index on 2nd and subsequent iterations of the loop. */ | 634 ** transient index on 2nd and subsequent iterations of the loop. */ |
| 1596 v = pParse->pVdbe; | 635 v = pParse->pVdbe; |
| 1597 assert( v!=0 ); | 636 assert( v!=0 ); |
| 1598 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v); | 637 addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v); |
| 1599 | 638 |
| 1600 /* Count the number of columns that will be added to the index | 639 /* Count the number of columns that will be added to the index |
| 1601 ** and used to match WHERE clause constraints */ | 640 ** and used to match WHERE clause constraints */ |
| 1602 nKeyCol = 0; | 641 nKeyCol = 0; |
| 1603 pTable = pSrc->pTab; | 642 pTable = pSrc->pTab; |
| 1604 pWCEnd = &pWC->a[pWC->nTerm]; | 643 pWCEnd = &pWC->a[pWC->nTerm]; |
| 1605 pLoop = pLevel->pWLoop; | 644 pLoop = pLevel->pWLoop; |
| 1606 idxCols = 0; | 645 idxCols = 0; |
| 1607 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ | 646 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ |
| 647 Expr *pExpr = pTerm->pExpr; |
| 648 assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */ |
| 649 || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */ |
| 650 || pLoop->prereq!=0 ); /* table of a LEFT JOIN */ |
| 651 if( pLoop->prereq==0 |
| 652 && (pTerm->wtFlags & TERM_VIRTUAL)==0 |
| 653 && !ExprHasProperty(pExpr, EP_FromJoin) |
| 654 && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){ |
| 655 pPartial = sqlite3ExprAnd(pParse->db, pPartial, |
| 656 sqlite3ExprDup(pParse->db, pExpr, 0)); |
| 657 } |
| 1608 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ | 658 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ |
| 1609 int iCol = pTerm->u.leftColumn; | 659 int iCol = pTerm->u.leftColumn; |
| 1610 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); | 660 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); |
| 1611 testcase( iCol==BMS ); | 661 testcase( iCol==BMS ); |
| 1612 testcase( iCol==BMS-1 ); | 662 testcase( iCol==BMS-1 ); |
| 1613 if( !sentWarning ){ | 663 if( !sentWarning ){ |
| 1614 sqlite3_log(SQLITE_WARNING_AUTOINDEX, | 664 sqlite3_log(SQLITE_WARNING_AUTOINDEX, |
| 1615 "automatic index on %s(%s)", pTable->zName, | 665 "automatic index on %s(%s)", pTable->zName, |
| 1616 pTable->aCol[iCol].zName); | 666 pTable->aCol[iCol].zName); |
| 1617 sentWarning = 1; | 667 sentWarning = 1; |
| 1618 } | 668 } |
| 1619 if( (idxCols & cMask)==0 ){ | 669 if( (idxCols & cMask)==0 ){ |
| 1620 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return; | 670 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){ |
| 671 goto end_auto_index_create; |
| 672 } |
| 1621 pLoop->aLTerm[nKeyCol++] = pTerm; | 673 pLoop->aLTerm[nKeyCol++] = pTerm; |
| 1622 idxCols |= cMask; | 674 idxCols |= cMask; |
| 1623 } | 675 } |
| 1624 } | 676 } |
| 1625 } | 677 } |
| 1626 assert( nKeyCol>0 ); | 678 assert( nKeyCol>0 ); |
| 1627 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; | 679 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol; |
| 1628 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED | 680 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED |
| 1629 | WHERE_AUTO_INDEX; | 681 | WHERE_AUTO_INDEX; |
| 1630 | 682 |
| 1631 /* Count the number of additional columns needed to create a | 683 /* Count the number of additional columns needed to create a |
| 1632 ** covering index. A "covering index" is an index that contains all | 684 ** covering index. A "covering index" is an index that contains all |
| 1633 ** columns that are needed by the query. With a covering index, the | 685 ** columns that are needed by the query. With a covering index, the |
| 1634 ** original table never needs to be accessed. Automatic indices must | 686 ** original table never needs to be accessed. Automatic indices must |
| 1635 ** be a covering index because the index will not be updated if the | 687 ** be a covering index because the index will not be updated if the |
| 1636 ** original table changes and the index and table cannot both be used | 688 ** original table changes and the index and table cannot both be used |
| 1637 ** if they go out of sync. | 689 ** if they go out of sync. |
| 1638 */ | 690 */ |
| 1639 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); | 691 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1)); |
| 1640 mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol; | 692 mxBitCol = MIN(BMS-1,pTable->nCol); |
| 1641 testcase( pTable->nCol==BMS-1 ); | 693 testcase( pTable->nCol==BMS-1 ); |
| 1642 testcase( pTable->nCol==BMS-2 ); | 694 testcase( pTable->nCol==BMS-2 ); |
| 1643 for(i=0; i<mxBitCol; i++){ | 695 for(i=0; i<mxBitCol; i++){ |
| 1644 if( extraCols & MASKBIT(i) ) nKeyCol++; | 696 if( extraCols & MASKBIT(i) ) nKeyCol++; |
| 1645 } | 697 } |
| 1646 if( pSrc->colUsed & MASKBIT(BMS-1) ){ | 698 if( pSrc->colUsed & MASKBIT(BMS-1) ){ |
| 1647 nKeyCol += pTable->nCol - BMS + 1; | 699 nKeyCol += pTable->nCol - BMS + 1; |
| 1648 } | 700 } |
| 1649 pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY; | |
| 1650 | 701 |
| 1651 /* Construct the Index object to describe this index */ | 702 /* Construct the Index object to describe this index */ |
| 1652 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); | 703 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed); |
| 1653 if( pIdx==0 ) return; | 704 if( pIdx==0 ) goto end_auto_index_create; |
| 1654 pLoop->u.btree.pIndex = pIdx; | 705 pLoop->u.btree.pIndex = pIdx; |
| 1655 pIdx->zName = "auto-index"; | 706 pIdx->zName = "auto-index"; |
| 1656 pIdx->pTable = pTable; | 707 pIdx->pTable = pTable; |
| 1657 n = 0; | 708 n = 0; |
| 1658 idxCols = 0; | 709 idxCols = 0; |
| 1659 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ | 710 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){ |
| 1660 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ | 711 if( termCanDriveIndex(pTerm, pSrc, notReady) ){ |
| 1661 int iCol = pTerm->u.leftColumn; | 712 int iCol = pTerm->u.leftColumn; |
| 1662 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); | 713 Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol); |
| 1663 testcase( iCol==BMS-1 ); | 714 testcase( iCol==BMS-1 ); |
| 1664 testcase( iCol==BMS ); | 715 testcase( iCol==BMS ); |
| 1665 if( (idxCols & cMask)==0 ){ | 716 if( (idxCols & cMask)==0 ){ |
| 1666 Expr *pX = pTerm->pExpr; | 717 Expr *pX = pTerm->pExpr; |
| 1667 idxCols |= cMask; | 718 idxCols |= cMask; |
| 1668 pIdx->aiColumn[n] = pTerm->u.leftColumn; | 719 pIdx->aiColumn[n] = pTerm->u.leftColumn; |
| 1669 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); | 720 pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight); |
| 1670 pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY"; | 721 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY; |
| 1671 n++; | 722 n++; |
| 1672 } | 723 } |
| 1673 } | 724 } |
| 1674 } | 725 } |
| 1675 assert( (u32)n==pLoop->u.btree.nEq ); | 726 assert( (u32)n==pLoop->u.btree.nEq ); |
| 1676 | 727 |
| 1677 /* Add additional columns needed to make the automatic index into | 728 /* Add additional columns needed to make the automatic index into |
| 1678 ** a covering index */ | 729 ** a covering index */ |
| 1679 for(i=0; i<mxBitCol; i++){ | 730 for(i=0; i<mxBitCol; i++){ |
| 1680 if( extraCols & MASKBIT(i) ){ | 731 if( extraCols & MASKBIT(i) ){ |
| 1681 pIdx->aiColumn[n] = i; | 732 pIdx->aiColumn[n] = i; |
| 1682 pIdx->azColl[n] = "BINARY"; | 733 pIdx->azColl[n] = sqlite3StrBINARY; |
| 1683 n++; | 734 n++; |
| 1684 } | 735 } |
| 1685 } | 736 } |
| 1686 if( pSrc->colUsed & MASKBIT(BMS-1) ){ | 737 if( pSrc->colUsed & MASKBIT(BMS-1) ){ |
| 1687 for(i=BMS-1; i<pTable->nCol; i++){ | 738 for(i=BMS-1; i<pTable->nCol; i++){ |
| 1688 pIdx->aiColumn[n] = i; | 739 pIdx->aiColumn[n] = i; |
| 1689 pIdx->azColl[n] = "BINARY"; | 740 pIdx->azColl[n] = sqlite3StrBINARY; |
| 1690 n++; | 741 n++; |
| 1691 } | 742 } |
| 1692 } | 743 } |
| 1693 assert( n==nKeyCol ); | 744 assert( n==nKeyCol ); |
| 1694 pIdx->aiColumn[n] = -1; | 745 pIdx->aiColumn[n] = XN_ROWID; |
| 1695 pIdx->azColl[n] = "BINARY"; | 746 pIdx->azColl[n] = sqlite3StrBINARY; |
| 1696 | 747 |
| 1697 /* Create the automatic index */ | 748 /* Create the automatic index */ |
| 1698 assert( pLevel->iIdxCur>=0 ); | 749 assert( pLevel->iIdxCur>=0 ); |
| 1699 pLevel->iIdxCur = pParse->nTab++; | 750 pLevel->iIdxCur = pParse->nTab++; |
| 1700 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); | 751 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1); |
| 1701 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); | 752 sqlite3VdbeSetP4KeyInfo(pParse, pIdx); |
| 1702 VdbeComment((v, "for %s", pTable->zName)); | 753 VdbeComment((v, "for %s", pTable->zName)); |
| 1703 | 754 |
| 1704 /* Fill the automatic index with content */ | 755 /* Fill the automatic index with content */ |
| 1705 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); | 756 sqlite3ExprCachePush(pParse); |
| 757 pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom]; |
| 758 if( pTabItem->fg.viaCoroutine ){ |
| 759 int regYield = pTabItem->regReturn; |
| 760 addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0); |
| 761 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); |
| 762 addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield); |
| 763 VdbeCoverage(v); |
| 764 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); |
| 765 }else{ |
| 766 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v); |
| 767 } |
| 768 if( pPartial ){ |
| 769 iContinue = sqlite3VdbeMakeLabel(v); |
| 770 sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL); |
| 771 pLoop->wsFlags |= WHERE_PARTIALIDX; |
| 772 } |
| 1706 regRecord = sqlite3GetTempReg(pParse); | 773 regRecord = sqlite3GetTempReg(pParse); |
| 1707 sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0); | 774 regBase = sqlite3GenerateIndexKey( |
| 775 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0 |
| 776 ); |
| 1708 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); | 777 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord); |
| 1709 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); | 778 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); |
| 1710 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); | 779 if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue); |
| 780 if( pTabItem->fg.viaCoroutine ){ |
| 781 sqlite3VdbeChangeP2(v, addrCounter, regBase+n); |
| 782 translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1); |
| 783 sqlite3VdbeGoto(v, addrTop); |
| 784 pTabItem->fg.viaCoroutine = 0; |
| 785 }else{ |
| 786 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v); |
| 787 } |
| 1711 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); | 788 sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX); |
| 1712 sqlite3VdbeJumpHere(v, addrTop); | 789 sqlite3VdbeJumpHere(v, addrTop); |
| 1713 sqlite3ReleaseTempReg(pParse, regRecord); | 790 sqlite3ReleaseTempReg(pParse, regRecord); |
| 791 sqlite3ExprCachePop(pParse); |
| 1714 | 792 |
| 1715 /* Jump here when skipping the initialization */ | 793 /* Jump here when skipping the initialization */ |
| 1716 sqlite3VdbeJumpHere(v, addrInit); | 794 sqlite3VdbeJumpHere(v, addrInit); |
| 795 |
| 796 end_auto_index_create: |
| 797 sqlite3ExprDelete(pParse->db, pPartial); |
| 1717 } | 798 } |
| 1718 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ | 799 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */ |
| 1719 | 800 |
| 1720 #ifndef SQLITE_OMIT_VIRTUALTABLE | 801 #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 1721 /* | 802 /* |
| 1722 ** Allocate and populate an sqlite3_index_info structure. It is the | 803 ** Allocate and populate an sqlite3_index_info structure. It is the |
| 1723 ** responsibility of the caller to eventually release the structure | 804 ** responsibility of the caller to eventually release the structure |
| 1724 ** by passing the pointer returned by this function to sqlite3_free(). | 805 ** by passing the pointer returned by this function to sqlite3_free(). |
| 1725 */ | 806 */ |
| 1726 static sqlite3_index_info *allocateIndexInfo( | 807 static sqlite3_index_info *allocateIndexInfo( |
| 1727 Parse *pParse, | 808 Parse *pParse, |
| 1728 WhereClause *pWC, | 809 WhereClause *pWC, |
| 810 Bitmask mUnusable, /* Ignore terms with these prereqs */ |
| 1729 struct SrcList_item *pSrc, | 811 struct SrcList_item *pSrc, |
| 1730 ExprList *pOrderBy | 812 ExprList *pOrderBy |
| 1731 ){ | 813 ){ |
| 1732 int i, j; | 814 int i, j; |
| 1733 int nTerm; | 815 int nTerm; |
| 1734 struct sqlite3_index_constraint *pIdxCons; | 816 struct sqlite3_index_constraint *pIdxCons; |
| 1735 struct sqlite3_index_orderby *pIdxOrderBy; | 817 struct sqlite3_index_orderby *pIdxOrderBy; |
| 1736 struct sqlite3_index_constraint_usage *pUsage; | 818 struct sqlite3_index_constraint_usage *pUsage; |
| 1737 WhereTerm *pTerm; | 819 WhereTerm *pTerm; |
| 1738 int nOrderBy; | 820 int nOrderBy; |
| 1739 sqlite3_index_info *pIdxInfo; | 821 sqlite3_index_info *pIdxInfo; |
| 1740 | 822 |
| 1741 /* Count the number of possible WHERE clause constraints referring | 823 /* Count the number of possible WHERE clause constraints referring |
| 1742 ** to this virtual table */ | 824 ** to this virtual table */ |
| 1743 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ | 825 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ |
| 1744 if( pTerm->leftCursor != pSrc->iCursor ) continue; | 826 if( pTerm->leftCursor != pSrc->iCursor ) continue; |
| 827 if( pTerm->prereqRight & mUnusable ) continue; |
| 1745 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); | 828 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); |
| 1746 testcase( pTerm->eOperator & WO_IN ); | 829 testcase( pTerm->eOperator & WO_IN ); |
| 1747 testcase( pTerm->eOperator & WO_ISNULL ); | 830 testcase( pTerm->eOperator & WO_ISNULL ); |
| 831 testcase( pTerm->eOperator & WO_IS ); |
| 1748 testcase( pTerm->eOperator & WO_ALL ); | 832 testcase( pTerm->eOperator & WO_ALL ); |
| 1749 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue; | 833 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue; |
| 1750 if( pTerm->wtFlags & TERM_VNULL ) continue; | 834 if( pTerm->wtFlags & TERM_VNULL ) continue; |
| 835 assert( pTerm->u.leftColumn>=(-1) ); |
| 1751 nTerm++; | 836 nTerm++; |
| 1752 } | 837 } |
| 1753 | 838 |
| 1754 /* If the ORDER BY clause contains only columns in the current | 839 /* If the ORDER BY clause contains only columns in the current |
| 1755 ** virtual table then allocate space for the aOrderBy part of | 840 ** virtual table then allocate space for the aOrderBy part of |
| 1756 ** the sqlite3_index_info structure. | 841 ** the sqlite3_index_info structure. |
| 1757 */ | 842 */ |
| 1758 nOrderBy = 0; | 843 nOrderBy = 0; |
| 1759 if( pOrderBy ){ | 844 if( pOrderBy ){ |
| 1760 int n = pOrderBy->nExpr; | 845 int n = pOrderBy->nExpr; |
| (...skipping 27 matching lines...) Expand all Loading... |
| 1788 *(int*)&pIdxInfo->nConstraint = nTerm; | 873 *(int*)&pIdxInfo->nConstraint = nTerm; |
| 1789 *(int*)&pIdxInfo->nOrderBy = nOrderBy; | 874 *(int*)&pIdxInfo->nOrderBy = nOrderBy; |
| 1790 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; | 875 *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons; |
| 1791 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; | 876 *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy; |
| 1792 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = | 877 *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage = |
| 1793 pUsage; | 878 pUsage; |
| 1794 | 879 |
| 1795 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ | 880 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ |
| 1796 u8 op; | 881 u8 op; |
| 1797 if( pTerm->leftCursor != pSrc->iCursor ) continue; | 882 if( pTerm->leftCursor != pSrc->iCursor ) continue; |
| 883 if( pTerm->prereqRight & mUnusable ) continue; |
| 1798 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); | 884 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) ); |
| 1799 testcase( pTerm->eOperator & WO_IN ); | 885 testcase( pTerm->eOperator & WO_IN ); |
| 886 testcase( pTerm->eOperator & WO_IS ); |
| 1800 testcase( pTerm->eOperator & WO_ISNULL ); | 887 testcase( pTerm->eOperator & WO_ISNULL ); |
| 1801 testcase( pTerm->eOperator & WO_ALL ); | 888 testcase( pTerm->eOperator & WO_ALL ); |
| 1802 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue; | 889 if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue; |
| 1803 if( pTerm->wtFlags & TERM_VNULL ) continue; | 890 if( pTerm->wtFlags & TERM_VNULL ) continue; |
| 891 assert( pTerm->u.leftColumn>=(-1) ); |
| 1804 pIdxCons[j].iColumn = pTerm->u.leftColumn; | 892 pIdxCons[j].iColumn = pTerm->u.leftColumn; |
| 1805 pIdxCons[j].iTermOffset = i; | 893 pIdxCons[j].iTermOffset = i; |
| 1806 op = (u8)pTerm->eOperator & WO_ALL; | 894 op = (u8)pTerm->eOperator & WO_ALL; |
| 1807 if( op==WO_IN ) op = WO_EQ; | 895 if( op==WO_IN ) op = WO_EQ; |
| 896 if( op==WO_MATCH ){ |
| 897 op = pTerm->eMatchOp; |
| 898 } |
| 1808 pIdxCons[j].op = op; | 899 pIdxCons[j].op = op; |
| 1809 /* The direct assignment in the previous line is possible only because | 900 /* The direct assignment in the previous line is possible only because |
| 1810 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The | 901 ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The |
| 1811 ** following asserts verify this fact. */ | 902 ** following asserts verify this fact. */ |
| 1812 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); | 903 assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ ); |
| 1813 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); | 904 assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT ); |
| 1814 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); | 905 assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE ); |
| 1815 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); | 906 assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT ); |
| 1816 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); | 907 assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE ); |
| 1817 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); | 908 assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH ); |
| (...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1866 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ | 957 if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){ |
| 1867 sqlite3ErrorMsg(pParse, | 958 sqlite3ErrorMsg(pParse, |
| 1868 "table %s: xBestIndex returned an invalid plan", pTab->zName); | 959 "table %s: xBestIndex returned an invalid plan", pTab->zName); |
| 1869 } | 960 } |
| 1870 } | 961 } |
| 1871 | 962 |
| 1872 return pParse->nErr; | 963 return pParse->nErr; |
| 1873 } | 964 } |
| 1874 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ | 965 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */ |
| 1875 | 966 |
| 1876 | |
| 1877 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | 967 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
| 1878 /* | 968 /* |
| 1879 ** Estimate the location of a particular key among all keys in an | 969 ** Estimate the location of a particular key among all keys in an |
| 1880 ** index. Store the results in aStat as follows: | 970 ** index. Store the results in aStat as follows: |
| 1881 ** | 971 ** |
| 1882 ** aStat[0] Est. number of rows less than pVal | 972 ** aStat[0] Est. number of rows less than pRec |
| 1883 ** aStat[1] Est. number of rows equal to pVal | 973 ** aStat[1] Est. number of rows equal to pRec |
| 1884 ** | 974 ** |
| 1885 ** Return SQLITE_OK on success. | 975 ** Return the index of the sample that is the smallest sample that |
| 976 ** is greater than or equal to pRec. Note that this index is not an index |
| 977 ** into the aSample[] array - it is an index into a virtual set of samples |
| 978 ** based on the contents of aSample[] and the number of fields in record |
| 979 ** pRec. |
| 1886 */ | 980 */ |
| 1887 static void whereKeyStats( | 981 static int whereKeyStats( |
| 1888 Parse *pParse, /* Database connection */ | 982 Parse *pParse, /* Database connection */ |
| 1889 Index *pIdx, /* Index to consider domain of */ | 983 Index *pIdx, /* Index to consider domain of */ |
| 1890 UnpackedRecord *pRec, /* Vector of values to consider */ | 984 UnpackedRecord *pRec, /* Vector of values to consider */ |
| 1891 int roundUp, /* Round up if true. Round down if false */ | 985 int roundUp, /* Round up if true. Round down if false */ |
| 1892 tRowcnt *aStat /* OUT: stats written here */ | 986 tRowcnt *aStat /* OUT: stats written here */ |
| 1893 ){ | 987 ){ |
| 1894 IndexSample *aSample = pIdx->aSample; | 988 IndexSample *aSample = pIdx->aSample; |
| 1895 int iCol; /* Index of required stats in anEq[] etc. */ | 989 int iCol; /* Index of required stats in anEq[] etc. */ |
| 990 int i; /* Index of first sample >= pRec */ |
| 991 int iSample; /* Smallest sample larger than or equal to pRec */ |
| 1896 int iMin = 0; /* Smallest sample not yet tested */ | 992 int iMin = 0; /* Smallest sample not yet tested */ |
| 1897 int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */ | |
| 1898 int iTest; /* Next sample to test */ | 993 int iTest; /* Next sample to test */ |
| 1899 int res; /* Result of comparison operation */ | 994 int res; /* Result of comparison operation */ |
| 995 int nField; /* Number of fields in pRec */ |
| 996 tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */ |
| 1900 | 997 |
| 1901 #ifndef SQLITE_DEBUG | 998 #ifndef SQLITE_DEBUG |
| 1902 UNUSED_PARAMETER( pParse ); | 999 UNUSED_PARAMETER( pParse ); |
| 1903 #endif | 1000 #endif |
| 1904 assert( pRec!=0 ); | 1001 assert( pRec!=0 ); |
| 1905 iCol = pRec->nField - 1; | |
| 1906 assert( pIdx->nSample>0 ); | 1002 assert( pIdx->nSample>0 ); |
| 1907 assert( pRec->nField>0 && iCol<pIdx->nSampleCol ); | 1003 assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol ); |
| 1004 |
| 1005 /* Do a binary search to find the first sample greater than or equal |
| 1006 ** to pRec. If pRec contains a single field, the set of samples to search |
| 1007 ** is simply the aSample[] array. If the samples in aSample[] contain more |
| 1008 ** than one fields, all fields following the first are ignored. |
| 1009 ** |
| 1010 ** If pRec contains N fields, where N is more than one, then as well as the |
| 1011 ** samples in aSample[] (truncated to N fields), the search also has to |
| 1012 ** consider prefixes of those samples. For example, if the set of samples |
| 1013 ** in aSample is: |
| 1014 ** |
| 1015 ** aSample[0] = (a, 5) |
| 1016 ** aSample[1] = (a, 10) |
| 1017 ** aSample[2] = (b, 5) |
| 1018 ** aSample[3] = (c, 100) |
| 1019 ** aSample[4] = (c, 105) |
| 1020 ** |
| 1021 ** Then the search space should ideally be the samples above and the |
| 1022 ** unique prefixes [a], [b] and [c]. But since that is hard to organize, |
| 1023 ** the code actually searches this set: |
| 1024 ** |
| 1025 ** 0: (a) |
| 1026 ** 1: (a, 5) |
| 1027 ** 2: (a, 10) |
| 1028 ** 3: (a, 10) |
| 1029 ** 4: (b) |
| 1030 ** 5: (b, 5) |
| 1031 ** 6: (c) |
| 1032 ** 7: (c, 100) |
| 1033 ** 8: (c, 105) |
| 1034 ** 9: (c, 105) |
| 1035 ** |
| 1036 ** For each sample in the aSample[] array, N samples are present in the |
| 1037 ** effective sample array. In the above, samples 0 and 1 are based on |
| 1038 ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc. |
| 1039 ** |
| 1040 ** Often, sample i of each block of N effective samples has (i+1) fields. |
| 1041 ** Except, each sample may be extended to ensure that it is greater than or |
| 1042 ** equal to the previous sample in the array. For example, in the above, |
| 1043 ** sample 2 is the first sample of a block of N samples, so at first it |
| 1044 ** appears that it should be 1 field in size. However, that would make it |
| 1045 ** smaller than sample 1, so the binary search would not work. As a result, |
| 1046 ** it is extended to two fields. The duplicates that this creates do not |
| 1047 ** cause any problems. |
| 1048 */ |
| 1049 nField = pRec->nField; |
| 1050 iCol = 0; |
| 1051 iSample = pIdx->nSample * nField; |
| 1908 do{ | 1052 do{ |
| 1909 iTest = (iMin+i)/2; | 1053 int iSamp; /* Index in aSample[] of test sample */ |
| 1910 res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec); | 1054 int n; /* Number of fields in test sample */ |
| 1055 |
| 1056 iTest = (iMin+iSample)/2; |
| 1057 iSamp = iTest / nField; |
| 1058 if( iSamp>0 ){ |
| 1059 /* The proposed effective sample is a prefix of sample aSample[iSamp]. |
| 1060 ** Specifically, the shortest prefix of at least (1 + iTest%nField) |
| 1061 ** fields that is greater than the previous effective sample. */ |
| 1062 for(n=(iTest % nField) + 1; n<nField; n++){ |
| 1063 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break; |
| 1064 } |
| 1065 }else{ |
| 1066 n = iTest + 1; |
| 1067 } |
| 1068 |
| 1069 pRec->nField = n; |
| 1070 res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec); |
| 1911 if( res<0 ){ | 1071 if( res<0 ){ |
| 1072 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1]; |
| 1912 iMin = iTest+1; | 1073 iMin = iTest+1; |
| 1074 }else if( res==0 && n<nField ){ |
| 1075 iLower = aSample[iSamp].anLt[n-1]; |
| 1076 iMin = iTest+1; |
| 1077 res = -1; |
| 1913 }else{ | 1078 }else{ |
| 1914 i = iTest; | 1079 iSample = iTest; |
| 1080 iCol = n-1; |
| 1915 } | 1081 } |
| 1916 }while( res && iMin<i ); | 1082 }while( res && iMin<iSample ); |
| 1083 i = iSample / nField; |
| 1917 | 1084 |
| 1918 #ifdef SQLITE_DEBUG | 1085 #ifdef SQLITE_DEBUG |
| 1919 /* The following assert statements check that the binary search code | 1086 /* The following assert statements check that the binary search code |
| 1920 ** above found the right answer. This block serves no purpose other | 1087 ** above found the right answer. This block serves no purpose other |
| 1921 ** than to invoke the asserts. */ | 1088 ** than to invoke the asserts. */ |
| 1922 if( res==0 ){ | 1089 if( pParse->db->mallocFailed==0 ){ |
| 1923 /* If (res==0) is true, then sample $i must be equal to pRec */ | 1090 if( res==0 ){ |
| 1924 assert( i<pIdx->nSample ); | 1091 /* If (res==0) is true, then pRec must be equal to sample i. */ |
| 1925 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) | 1092 assert( i<pIdx->nSample ); |
| 1926 || pParse->db->mallocFailed ); | 1093 assert( iCol==nField-1 ); |
| 1927 }else{ | 1094 pRec->nField = nField; |
| 1928 /* Otherwise, pRec must be smaller than sample $i and larger than | 1095 assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) |
| 1929 ** sample ($i-1). */ | 1096 || pParse->db->mallocFailed |
| 1930 assert( i==pIdx->nSample | 1097 ); |
| 1931 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 | 1098 }else{ |
| 1932 || pParse->db->mallocFailed ); | 1099 /* Unless i==pIdx->nSample, indicating that pRec is larger than |
| 1933 assert( i==0 | 1100 ** all samples in the aSample[] array, pRec must be smaller than the |
| 1934 || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 | 1101 ** (iCol+1) field prefix of sample i. */ |
| 1935 || pParse->db->mallocFailed ); | 1102 assert( i<=pIdx->nSample && i>=0 ); |
| 1103 pRec->nField = iCol+1; |
| 1104 assert( i==pIdx->nSample |
| 1105 || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0 |
| 1106 || pParse->db->mallocFailed ); |
| 1107 |
| 1108 /* if i==0 and iCol==0, then record pRec is smaller than all samples |
| 1109 ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must |
| 1110 ** be greater than or equal to the (iCol) field prefix of sample i. |
| 1111 ** If (i>0), then pRec must also be greater than sample (i-1). */ |
| 1112 if( iCol>0 ){ |
| 1113 pRec->nField = iCol; |
| 1114 assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0 |
| 1115 || pParse->db->mallocFailed ); |
| 1116 } |
| 1117 if( i>0 ){ |
| 1118 pRec->nField = nField; |
| 1119 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0 |
| 1120 || pParse->db->mallocFailed ); |
| 1121 } |
| 1122 } |
| 1936 } | 1123 } |
| 1937 #endif /* ifdef SQLITE_DEBUG */ | 1124 #endif /* ifdef SQLITE_DEBUG */ |
| 1938 | 1125 |
| 1939 /* At this point, aSample[i] is the first sample that is greater than | |
| 1940 ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less | |
| 1941 ** than pVal. If aSample[i]==pVal, then res==0. | |
| 1942 */ | |
| 1943 if( res==0 ){ | 1126 if( res==0 ){ |
| 1127 /* Record pRec is equal to sample i */ |
| 1128 assert( iCol==nField-1 ); |
| 1944 aStat[0] = aSample[i].anLt[iCol]; | 1129 aStat[0] = aSample[i].anLt[iCol]; |
| 1945 aStat[1] = aSample[i].anEq[iCol]; | 1130 aStat[1] = aSample[i].anEq[iCol]; |
| 1946 }else{ | 1131 }else{ |
| 1947 tRowcnt iLower, iUpper, iGap; | 1132 /* At this point, the (iCol+1) field prefix of aSample[i] is the first |
| 1948 if( i==0 ){ | 1133 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec |
| 1949 iLower = 0; | 1134 ** is larger than all samples in the array. */ |
| 1950 iUpper = aSample[0].anLt[iCol]; | 1135 tRowcnt iUpper, iGap; |
| 1136 if( i>=pIdx->nSample ){ |
| 1137 iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]); |
| 1951 }else{ | 1138 }else{ |
| 1952 i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]); | 1139 iUpper = aSample[i].anLt[iCol]; |
| 1953 iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol]; | |
| 1954 iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol]; | |
| 1955 } | 1140 } |
| 1956 aStat[1] = pIdx->aAvgEq[iCol]; | 1141 |
| 1957 if( iLower>=iUpper ){ | 1142 if( iLower>=iUpper ){ |
| 1958 iGap = 0; | 1143 iGap = 0; |
| 1959 }else{ | 1144 }else{ |
| 1960 iGap = iUpper - iLower; | 1145 iGap = iUpper - iLower; |
| 1961 } | 1146 } |
| 1962 if( roundUp ){ | 1147 if( roundUp ){ |
| 1963 iGap = (iGap*2)/3; | 1148 iGap = (iGap*2)/3; |
| 1964 }else{ | 1149 }else{ |
| 1965 iGap = iGap/3; | 1150 iGap = iGap/3; |
| 1966 } | 1151 } |
| 1967 aStat[0] = iLower + iGap; | 1152 aStat[0] = iLower + iGap; |
| 1153 aStat[1] = pIdx->aAvgEq[iCol]; |
| 1968 } | 1154 } |
| 1155 |
| 1156 /* Restore the pRec->nField value before returning. */ |
| 1157 pRec->nField = nField; |
| 1158 return i; |
| 1969 } | 1159 } |
| 1970 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ | 1160 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ |
| 1971 | 1161 |
| 1972 /* | 1162 /* |
| 1973 ** If it is not NULL, pTerm is a term that provides an upper or lower | 1163 ** If it is not NULL, pTerm is a term that provides an upper or lower |
| 1974 ** bound on a range scan. Without considering pTerm, it is estimated | 1164 ** bound on a range scan. Without considering pTerm, it is estimated |
| 1975 ** that the scan will visit nNew rows. This function returns the number | 1165 ** that the scan will visit nNew rows. This function returns the number |
| 1976 ** estimated to be visited after taking pTerm into account. | 1166 ** estimated to be visited after taking pTerm into account. |
| 1977 ** | 1167 ** |
| 1978 ** If the user explicitly specified a likelihood() value for this term, | 1168 ** If the user explicitly specified a likelihood() value for this term, |
| 1979 ** then the return value is the likelihood multiplied by the number of | 1169 ** then the return value is the likelihood multiplied by the number of |
| 1980 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term | 1170 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term |
| 1981 ** has a likelihood of 0.50, and any other term a likelihood of 0.25. | 1171 ** has a likelihood of 0.50, and any other term a likelihood of 0.25. |
| 1982 */ | 1172 */ |
| 1983 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ | 1173 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){ |
| 1984 LogEst nRet = nNew; | 1174 LogEst nRet = nNew; |
| 1985 if( pTerm ){ | 1175 if( pTerm ){ |
| 1986 if( pTerm->truthProb<=0 ){ | 1176 if( pTerm->truthProb<=0 ){ |
| 1987 nRet += pTerm->truthProb; | 1177 nRet += pTerm->truthProb; |
| 1988 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ | 1178 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){ |
| 1989 nRet -= 20; assert( 20==sqlite3LogEst(4) ); | 1179 nRet -= 20; assert( 20==sqlite3LogEst(4) ); |
| 1990 } | 1180 } |
| 1991 } | 1181 } |
| 1992 return nRet; | 1182 return nRet; |
| 1993 } | 1183 } |
| 1994 | 1184 |
| 1185 |
| 1186 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
| 1187 /* |
| 1188 ** Return the affinity for a single column of an index. |
| 1189 */ |
| 1190 static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){ |
| 1191 assert( iCol>=0 && iCol<pIdx->nColumn ); |
| 1192 if( !pIdx->zColAff ){ |
| 1193 if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB; |
| 1194 } |
| 1195 return pIdx->zColAff[iCol]; |
| 1196 } |
| 1197 #endif |
| 1198 |
| 1199 |
| 1995 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | 1200 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
| 1996 /* | 1201 /* |
| 1997 ** This function is called to estimate the number of rows visited by a | 1202 ** This function is called to estimate the number of rows visited by a |
| 1998 ** range-scan on a skip-scan index. For example: | 1203 ** range-scan on a skip-scan index. For example: |
| 1999 ** | 1204 ** |
| 2000 ** CREATE INDEX i1 ON t1(a, b, c); | 1205 ** CREATE INDEX i1 ON t1(a, b, c); |
| 2001 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?; | 1206 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?; |
| 2002 ** | 1207 ** |
| 2003 ** Value pLoop->nOut is currently set to the estimated number of rows | 1208 ** Value pLoop->nOut is currently set to the estimated number of rows |
| 2004 ** visited for scanning (a=? AND b=?). This function reduces that estimate | 1209 ** visited for scanning (a=? AND b=?). This function reduces that estimate |
| (...skipping 29 matching lines...) Expand all Loading... |
| 2034 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ | 1239 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ |
| 2035 WhereLoop *pLoop, /* Update the .nOut value of this loop */ | 1240 WhereLoop *pLoop, /* Update the .nOut value of this loop */ |
| 2036 int *pbDone /* Set to true if at least one expr. value extracted */ | 1241 int *pbDone /* Set to true if at least one expr. value extracted */ |
| 2037 ){ | 1242 ){ |
| 2038 Index *p = pLoop->u.btree.pIndex; | 1243 Index *p = pLoop->u.btree.pIndex; |
| 2039 int nEq = pLoop->u.btree.nEq; | 1244 int nEq = pLoop->u.btree.nEq; |
| 2040 sqlite3 *db = pParse->db; | 1245 sqlite3 *db = pParse->db; |
| 2041 int nLower = -1; | 1246 int nLower = -1; |
| 2042 int nUpper = p->nSample+1; | 1247 int nUpper = p->nSample+1; |
| 2043 int rc = SQLITE_OK; | 1248 int rc = SQLITE_OK; |
| 2044 int iCol = p->aiColumn[nEq]; | 1249 u8 aff = sqlite3IndexColumnAffinity(db, p, nEq); |
| 2045 u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER; | |
| 2046 CollSeq *pColl; | 1250 CollSeq *pColl; |
| 2047 | 1251 |
| 2048 sqlite3_value *p1 = 0; /* Value extracted from pLower */ | 1252 sqlite3_value *p1 = 0; /* Value extracted from pLower */ |
| 2049 sqlite3_value *p2 = 0; /* Value extracted from pUpper */ | 1253 sqlite3_value *p2 = 0; /* Value extracted from pUpper */ |
| 2050 sqlite3_value *pVal = 0; /* Value extracted from record */ | 1254 sqlite3_value *pVal = 0; /* Value extracted from record */ |
| 2051 | 1255 |
| 2052 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); | 1256 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]); |
| 2053 if( pLower ){ | 1257 if( pLower ){ |
| 2054 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); | 1258 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1); |
| 2055 nLower = 0; | 1259 nLower = 0; |
| (...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 2109 ** example, assuming that index p is on t1(a): | 1313 ** example, assuming that index p is on t1(a): |
| 2110 ** | 1314 ** |
| 2111 ** ... FROM t1 WHERE a > ? AND a < ? ... | 1315 ** ... FROM t1 WHERE a > ? AND a < ? ... |
| 2112 ** |_____| |_____| | 1316 ** |_____| |_____| |
| 2113 ** | | | 1317 ** | | |
| 2114 ** pLower pUpper | 1318 ** pLower pUpper |
| 2115 ** | 1319 ** |
| 2116 ** If either of the upper or lower bound is not present, then NULL is passed in | 1320 ** If either of the upper or lower bound is not present, then NULL is passed in |
| 2117 ** place of the corresponding WhereTerm. | 1321 ** place of the corresponding WhereTerm. |
| 2118 ** | 1322 ** |
| 2119 ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index | 1323 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index |
| 2120 ** column subject to the range constraint. Or, equivalently, the number of | 1324 ** column subject to the range constraint. Or, equivalently, the number of |
| 2121 ** equality constraints optimized by the proposed index scan. For example, | 1325 ** equality constraints optimized by the proposed index scan. For example, |
| 2122 ** assuming index p is on t1(a, b), and the SQL query is: | 1326 ** assuming index p is on t1(a, b), and the SQL query is: |
| 2123 ** | 1327 ** |
| 2124 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... | 1328 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ... |
| 2125 ** | 1329 ** |
| 2126 ** then nEq is set to 1 (as the range restricted column, b, is the second | 1330 ** then nEq is set to 1 (as the range restricted column, b, is the second |
| 2127 ** left-most column of the index). Or, if the query is: | 1331 ** left-most column of the index). Or, if the query is: |
| 2128 ** | 1332 ** |
| 2129 ** ... FROM t1 WHERE a > ? AND a < ? ... | 1333 ** ... FROM t1 WHERE a > ? AND a < ? ... |
| 2130 ** | 1334 ** |
| 2131 ** then nEq is set to 0. | 1335 ** then nEq is set to 0. |
| 2132 ** | 1336 ** |
| 2133 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the | 1337 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the |
| 2134 ** number of rows that the index scan is expected to visit without | 1338 ** number of rows that the index scan is expected to visit without |
| 2135 ** considering the range constraints. If nEq is 0, this is the number of | 1339 ** considering the range constraints. If nEq is 0, then *pnOut is the number of |
| 2136 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) | 1340 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced) |
| 2137 ** to account for the range constraints pLower and pUpper. | 1341 ** to account for the range constraints pLower and pUpper. |
| 2138 ** | 1342 ** |
| 2139 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be | 1343 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be |
| 2140 ** used, a single range inequality reduces the search space by a factor of 4. | 1344 ** used, a single range inequality reduces the search space by a factor of 4. |
| 2141 ** and a pair of constraints (x>? AND x<?) reduces the expected number of | 1345 ** and a pair of constraints (x>? AND x<?) reduces the expected number of |
| 2142 ** rows visited by a factor of 64. | 1346 ** rows visited by a factor of 64. |
| 2143 */ | 1347 */ |
| 2144 static int whereRangeScanEst( | 1348 static int whereRangeScanEst( |
| 2145 Parse *pParse, /* Parsing & code generating context */ | 1349 Parse *pParse, /* Parsing & code generating context */ |
| 2146 WhereLoopBuilder *pBuilder, | 1350 WhereLoopBuilder *pBuilder, |
| 2147 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ | 1351 WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */ |
| 2148 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ | 1352 WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */ |
| 2149 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ | 1353 WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */ |
| 2150 ){ | 1354 ){ |
| 2151 int rc = SQLITE_OK; | 1355 int rc = SQLITE_OK; |
| 2152 int nOut = pLoop->nOut; | 1356 int nOut = pLoop->nOut; |
| 2153 LogEst nNew; | 1357 LogEst nNew; |
| 2154 | 1358 |
| 2155 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | 1359 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
| 2156 Index *p = pLoop->u.btree.pIndex; | 1360 Index *p = pLoop->u.btree.pIndex; |
| 2157 int nEq = pLoop->u.btree.nEq; | 1361 int nEq = pLoop->u.btree.nEq; |
| 2158 | 1362 |
| 2159 if( p->nSample>0 | 1363 if( p->nSample>0 && nEq<p->nSampleCol ){ |
| 2160 && nEq<p->nSampleCol | |
| 2161 && OptimizationEnabled(pParse->db, SQLITE_Stat3) | |
| 2162 ){ | |
| 2163 if( nEq==pBuilder->nRecValid ){ | 1364 if( nEq==pBuilder->nRecValid ){ |
| 2164 UnpackedRecord *pRec = pBuilder->pRec; | 1365 UnpackedRecord *pRec = pBuilder->pRec; |
| 2165 tRowcnt a[2]; | 1366 tRowcnt a[2]; |
| 2166 u8 aff; | 1367 u8 aff; |
| 2167 | 1368 |
| 2168 /* Variable iLower will be set to the estimate of the number of rows in | 1369 /* Variable iLower will be set to the estimate of the number of rows in |
| 2169 ** the index that are less than the lower bound of the range query. The | 1370 ** the index that are less than the lower bound of the range query. The |
| 2170 ** lower bound being the concatenation of $P and $L, where $P is the | 1371 ** lower bound being the concatenation of $P and $L, where $P is the |
| 2171 ** key-prefix formed by the nEq values matched against the nEq left-most | 1372 ** key-prefix formed by the nEq values matched against the nEq left-most |
| 2172 ** columns of the index, and $L is the value in pLower. | 1373 ** columns of the index, and $L is the value in pLower. |
| 2173 ** | 1374 ** |
| 2174 ** Or, if pLower is NULL or $L cannot be extracted from it (because it | 1375 ** Or, if pLower is NULL or $L cannot be extracted from it (because it |
| 2175 ** is not a simple variable or literal value), the lower bound of the | 1376 ** is not a simple variable or literal value), the lower bound of the |
| 2176 ** range is $P. Due to a quirk in the way whereKeyStats() works, even | 1377 ** range is $P. Due to a quirk in the way whereKeyStats() works, even |
| 2177 ** if $L is available, whereKeyStats() is called for both ($P) and | 1378 ** if $L is available, whereKeyStats() is called for both ($P) and |
| 2178 ** ($P:$L) and the larger of the two returned values used. | 1379 ** ($P:$L) and the larger of the two returned values is used. |
| 2179 ** | 1380 ** |
| 2180 ** Similarly, iUpper is to be set to the estimate of the number of rows | 1381 ** Similarly, iUpper is to be set to the estimate of the number of rows |
| 2181 ** less than the upper bound of the range query. Where the upper bound | 1382 ** less than the upper bound of the range query. Where the upper bound |
| 2182 ** is either ($P) or ($P:$U). Again, even if $U is available, both values | 1383 ** is either ($P) or ($P:$U). Again, even if $U is available, both values |
| 2183 ** of iUpper are requested of whereKeyStats() and the smaller used. | 1384 ** of iUpper are requested of whereKeyStats() and the smaller used. |
| 1385 ** |
| 1386 ** The number of rows between the two bounds is then just iUpper-iLower. |
| 2184 */ | 1387 */ |
| 2185 tRowcnt iLower; | 1388 tRowcnt iLower; /* Rows less than the lower bound */ |
| 2186 tRowcnt iUpper; | 1389 tRowcnt iUpper; /* Rows less than the upper bound */ |
| 1390 int iLwrIdx = -2; /* aSample[] for the lower bound */ |
| 1391 int iUprIdx = -1; /* aSample[] for the upper bound */ |
| 2187 | 1392 |
| 2188 if( pRec ){ | 1393 if( pRec ){ |
| 2189 testcase( pRec->nField!=pBuilder->nRecValid ); | 1394 testcase( pRec->nField!=pBuilder->nRecValid ); |
| 2190 pRec->nField = pBuilder->nRecValid; | 1395 pRec->nField = pBuilder->nRecValid; |
| 2191 } | 1396 } |
| 2192 if( nEq==p->nKeyCol ){ | 1397 aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq); |
| 2193 aff = SQLITE_AFF_INTEGER; | 1398 assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER ); |
| 2194 }else{ | |
| 2195 aff = p->pTable->aCol[p->aiColumn[nEq]].affinity; | |
| 2196 } | |
| 2197 /* Determine iLower and iUpper using ($P) only. */ | 1399 /* Determine iLower and iUpper using ($P) only. */ |
| 2198 if( nEq==0 ){ | 1400 if( nEq==0 ){ |
| 2199 iLower = 0; | 1401 iLower = 0; |
| 2200 iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]); | 1402 iUpper = p->nRowEst0; |
| 2201 }else{ | 1403 }else{ |
| 2202 /* Note: this call could be optimized away - since the same values must | 1404 /* Note: this call could be optimized away - since the same values must |
| 2203 ** have been requested when testing key $P in whereEqualScanEst(). */ | 1405 ** have been requested when testing key $P in whereEqualScanEst(). */ |
| 2204 whereKeyStats(pParse, p, pRec, 0, a); | 1406 whereKeyStats(pParse, p, pRec, 0, a); |
| 2205 iLower = a[0]; | 1407 iLower = a[0]; |
| 2206 iUpper = a[0] + a[1]; | 1408 iUpper = a[0] + a[1]; |
| 2207 } | 1409 } |
| 2208 | 1410 |
| 2209 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 ); | 1411 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 ); |
| 2210 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); | 1412 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 ); |
| 2211 assert( p->aSortOrder!=0 ); | 1413 assert( p->aSortOrder!=0 ); |
| 2212 if( p->aSortOrder[nEq] ){ | 1414 if( p->aSortOrder[nEq] ){ |
| 2213 /* The roles of pLower and pUpper are swapped for a DESC index */ | 1415 /* The roles of pLower and pUpper are swapped for a DESC index */ |
| 2214 SWAP(WhereTerm*, pLower, pUpper); | 1416 SWAP(WhereTerm*, pLower, pUpper); |
| 2215 } | 1417 } |
| 2216 | 1418 |
| 2217 /* If possible, improve on the iLower estimate using ($P:$L). */ | 1419 /* If possible, improve on the iLower estimate using ($P:$L). */ |
| 2218 if( pLower ){ | 1420 if( pLower ){ |
| 2219 int bOk; /* True if value is extracted from pExpr */ | 1421 int bOk; /* True if value is extracted from pExpr */ |
| 2220 Expr *pExpr = pLower->pExpr->pRight; | 1422 Expr *pExpr = pLower->pExpr->pRight; |
| 2221 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); | 1423 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); |
| 2222 if( rc==SQLITE_OK && bOk ){ | 1424 if( rc==SQLITE_OK && bOk ){ |
| 2223 tRowcnt iNew; | 1425 tRowcnt iNew; |
| 2224 whereKeyStats(pParse, p, pRec, 0, a); | 1426 iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a); |
| 2225 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0); | 1427 iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0); |
| 2226 if( iNew>iLower ) iLower = iNew; | 1428 if( iNew>iLower ) iLower = iNew; |
| 2227 nOut--; | 1429 nOut--; |
| 2228 pLower = 0; | 1430 pLower = 0; |
| 2229 } | 1431 } |
| 2230 } | 1432 } |
| 2231 | 1433 |
| 2232 /* If possible, improve on the iUpper estimate using ($P:$U). */ | 1434 /* If possible, improve on the iUpper estimate using ($P:$U). */ |
| 2233 if( pUpper ){ | 1435 if( pUpper ){ |
| 2234 int bOk; /* True if value is extracted from pExpr */ | 1436 int bOk; /* True if value is extracted from pExpr */ |
| 2235 Expr *pExpr = pUpper->pExpr->pRight; | 1437 Expr *pExpr = pUpper->pExpr->pRight; |
| 2236 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); | 1438 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk); |
| 2237 if( rc==SQLITE_OK && bOk ){ | 1439 if( rc==SQLITE_OK && bOk ){ |
| 2238 tRowcnt iNew; | 1440 tRowcnt iNew; |
| 2239 whereKeyStats(pParse, p, pRec, 1, a); | 1441 iUprIdx = whereKeyStats(pParse, p, pRec, 1, a); |
| 2240 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0); | 1442 iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0); |
| 2241 if( iNew<iUpper ) iUpper = iNew; | 1443 if( iNew<iUpper ) iUpper = iNew; |
| 2242 nOut--; | 1444 nOut--; |
| 2243 pUpper = 0; | 1445 pUpper = 0; |
| 2244 } | 1446 } |
| 2245 } | 1447 } |
| 2246 | 1448 |
| 2247 pBuilder->pRec = pRec; | 1449 pBuilder->pRec = pRec; |
| 2248 if( rc==SQLITE_OK ){ | 1450 if( rc==SQLITE_OK ){ |
| 2249 if( iUpper>iLower ){ | 1451 if( iUpper>iLower ){ |
| 2250 nNew = sqlite3LogEst(iUpper - iLower); | 1452 nNew = sqlite3LogEst(iUpper - iLower); |
| 1453 /* TUNING: If both iUpper and iLower are derived from the same |
| 1454 ** sample, then assume they are 4x more selective. This brings |
| 1455 ** the estimated selectivity more in line with what it would be |
| 1456 ** if estimated without the use of STAT3/4 tables. */ |
| 1457 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) ); |
| 2251 }else{ | 1458 }else{ |
| 2252 nNew = 10; assert( 10==sqlite3LogEst(2) ); | 1459 nNew = 10; assert( 10==sqlite3LogEst(2) ); |
| 2253 } | 1460 } |
| 2254 if( nNew<nOut ){ | 1461 if( nNew<nOut ){ |
| 2255 nOut = nNew; | 1462 nOut = nNew; |
| 2256 } | 1463 } |
| 2257 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n", | 1464 WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n", |
| 2258 (u32)iLower, (u32)iUpper, nOut)); | 1465 (u32)iLower, (u32)iUpper, nOut)); |
| 2259 } | 1466 } |
| 2260 }else{ | 1467 }else{ |
| 2261 int bDone = 0; | 1468 int bDone = 0; |
| 2262 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone); | 1469 rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone); |
| 2263 if( bDone ) return rc; | 1470 if( bDone ) return rc; |
| 2264 } | 1471 } |
| 2265 } | 1472 } |
| 2266 #else | 1473 #else |
| 2267 UNUSED_PARAMETER(pParse); | 1474 UNUSED_PARAMETER(pParse); |
| 2268 UNUSED_PARAMETER(pBuilder); | 1475 UNUSED_PARAMETER(pBuilder); |
| 2269 assert( pLower || pUpper ); | 1476 assert( pLower || pUpper ); |
| 2270 #endif | 1477 #endif |
| 2271 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 ); | 1478 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 ); |
| 2272 nNew = whereRangeAdjust(pLower, nOut); | 1479 nNew = whereRangeAdjust(pLower, nOut); |
| 2273 nNew = whereRangeAdjust(pUpper, nNew); | 1480 nNew = whereRangeAdjust(pUpper, nNew); |
| 2274 | 1481 |
| 2275 /* TUNING: If there is both an upper and lower limit, assume the range is | 1482 /* TUNING: If there is both an upper and lower limit and neither limit |
| 1483 ** has an application-defined likelihood(), assume the range is |
| 2276 ** reduced by an additional 75%. This means that, by default, an open-ended | 1484 ** reduced by an additional 75%. This means that, by default, an open-ended |
| 2277 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the | 1485 ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the |
| 2278 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to | 1486 ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to |
| 2279 ** match 1/64 of the index. */ | 1487 ** match 1/64 of the index. */ |
| 2280 if( pLower && pUpper ) nNew -= 20; | 1488 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){ |
| 1489 nNew -= 20; |
| 1490 } |
| 2281 | 1491 |
| 2282 nOut -= (pLower!=0) + (pUpper!=0); | 1492 nOut -= (pLower!=0) + (pUpper!=0); |
| 2283 if( nNew<10 ) nNew = 10; | 1493 if( nNew<10 ) nNew = 10; |
| 2284 if( nNew<nOut ) nOut = nNew; | 1494 if( nNew<nOut ) nOut = nNew; |
| 2285 #if defined(WHERETRACE_ENABLED) | 1495 #if defined(WHERETRACE_ENABLED) |
| 2286 if( pLoop->nOut>nOut ){ | 1496 if( pLoop->nOut>nOut ){ |
| 2287 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n", | 1497 WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n", |
| 2288 pLoop->nOut, nOut)); | 1498 pLoop->nOut, nOut)); |
| 2289 } | 1499 } |
| 2290 #endif | 1500 #endif |
| (...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 2336 return SQLITE_NOTFOUND; | 1546 return SQLITE_NOTFOUND; |
| 2337 } | 1547 } |
| 2338 | 1548 |
| 2339 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() | 1549 /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue() |
| 2340 ** below would return the same value. */ | 1550 ** below would return the same value. */ |
| 2341 if( nEq>=p->nColumn ){ | 1551 if( nEq>=p->nColumn ){ |
| 2342 *pnRow = 1; | 1552 *pnRow = 1; |
| 2343 return SQLITE_OK; | 1553 return SQLITE_OK; |
| 2344 } | 1554 } |
| 2345 | 1555 |
| 2346 aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity; | 1556 aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1); |
| 2347 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk); | 1557 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk); |
| 2348 pBuilder->pRec = pRec; | 1558 pBuilder->pRec = pRec; |
| 2349 if( rc!=SQLITE_OK ) return rc; | 1559 if( rc!=SQLITE_OK ) return rc; |
| 2350 if( bOk==0 ) return SQLITE_NOTFOUND; | 1560 if( bOk==0 ) return SQLITE_NOTFOUND; |
| 2351 pBuilder->nRecValid = nEq; | 1561 pBuilder->nRecValid = nEq; |
| 2352 | 1562 |
| 2353 whereKeyStats(pParse, p, pRec, 0, a); | 1563 whereKeyStats(pParse, p, pRec, 0, a); |
| 2354 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1])); | 1564 WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1])); |
| 2355 *pnRow = a[1]; | 1565 *pnRow = a[1]; |
| 2356 | 1566 |
| (...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 2400 if( rc==SQLITE_OK ){ | 1610 if( rc==SQLITE_OK ){ |
| 2401 if( nRowEst > nRow0 ) nRowEst = nRow0; | 1611 if( nRowEst > nRow0 ) nRowEst = nRow0; |
| 2402 *pnRow = nRowEst; | 1612 *pnRow = nRowEst; |
| 2403 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst)); | 1613 WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst)); |
| 2404 } | 1614 } |
| 2405 assert( pBuilder->nRecValid==nRecValid ); | 1615 assert( pBuilder->nRecValid==nRecValid ); |
| 2406 return rc; | 1616 return rc; |
| 2407 } | 1617 } |
| 2408 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ | 1618 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */ |
| 2409 | 1619 |
| 2410 /* | |
| 2411 ** Disable a term in the WHERE clause. Except, do not disable the term | |
| 2412 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON | |
| 2413 ** or USING clause of that join. | |
| 2414 ** | |
| 2415 ** Consider the term t2.z='ok' in the following queries: | |
| 2416 ** | |
| 2417 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok' | |
| 2418 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok' | |
| 2419 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok' | |
| 2420 ** | |
| 2421 ** The t2.z='ok' is disabled in the in (2) because it originates | |
| 2422 ** in the ON clause. The term is disabled in (3) because it is not part | |
| 2423 ** of a LEFT OUTER JOIN. In (1), the term is not disabled. | |
| 2424 ** | |
| 2425 ** Disabling a term causes that term to not be tested in the inner loop | |
| 2426 ** of the join. Disabling is an optimization. When terms are satisfied | |
| 2427 ** by indices, we disable them to prevent redundant tests in the inner | |
| 2428 ** loop. We would get the correct results if nothing were ever disabled, | |
| 2429 ** but joins might run a little slower. The trick is to disable as much | |
| 2430 ** as we can without disabling too much. If we disabled in (1), we'd get | |
| 2431 ** the wrong answer. See ticket #813. | |
| 2432 */ | |
| 2433 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ | |
| 2434 if( pTerm | |
| 2435 && (pTerm->wtFlags & TERM_CODED)==0 | |
| 2436 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) | |
| 2437 && (pLevel->notReady & pTerm->prereqAll)==0 | |
| 2438 ){ | |
| 2439 pTerm->wtFlags |= TERM_CODED; | |
| 2440 if( pTerm->iParent>=0 ){ | |
| 2441 WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent]; | |
| 2442 if( (--pOther->nChild)==0 ){ | |
| 2443 disableTerm(pLevel, pOther); | |
| 2444 } | |
| 2445 } | |
| 2446 } | |
| 2447 } | |
| 2448 | |
| 2449 /* | |
| 2450 ** Code an OP_Affinity opcode to apply the column affinity string zAff | |
| 2451 ** to the n registers starting at base. | |
| 2452 ** | |
| 2453 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the | |
| 2454 ** beginning and end of zAff are ignored. If all entries in zAff are | |
| 2455 ** SQLITE_AFF_NONE, then no code gets generated. | |
| 2456 ** | |
| 2457 ** This routine makes its own copy of zAff so that the caller is free | |
| 2458 ** to modify zAff after this routine returns. | |
| 2459 */ | |
| 2460 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){ | |
| 2461 Vdbe *v = pParse->pVdbe; | |
| 2462 if( zAff==0 ){ | |
| 2463 assert( pParse->db->mallocFailed ); | |
| 2464 return; | |
| 2465 } | |
| 2466 assert( v!=0 ); | |
| 2467 | |
| 2468 /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning | |
| 2469 ** and end of the affinity string. | |
| 2470 */ | |
| 2471 while( n>0 && zAff[0]==SQLITE_AFF_NONE ){ | |
| 2472 n--; | |
| 2473 base++; | |
| 2474 zAff++; | |
| 2475 } | |
| 2476 while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){ | |
| 2477 n--; | |
| 2478 } | |
| 2479 | |
| 2480 /* Code the OP_Affinity opcode if there is anything left to do. */ | |
| 2481 if( n>0 ){ | |
| 2482 sqlite3VdbeAddOp2(v, OP_Affinity, base, n); | |
| 2483 sqlite3VdbeChangeP4(v, -1, zAff, n); | |
| 2484 sqlite3ExprCacheAffinityChange(pParse, base, n); | |
| 2485 } | |
| 2486 } | |
| 2487 | |
| 2488 | |
| 2489 /* | |
| 2490 ** Generate code for a single equality term of the WHERE clause. An equality | |
| 2491 ** term can be either X=expr or X IN (...). pTerm is the term to be | |
| 2492 ** coded. | |
| 2493 ** | |
| 2494 ** The current value for the constraint is left in register iReg. | |
| 2495 ** | |
| 2496 ** For a constraint of the form X=expr, the expression is evaluated and its | |
| 2497 ** result is left on the stack. For constraints of the form X IN (...) | |
| 2498 ** this routine sets up a loop that will iterate over all values of X. | |
| 2499 */ | |
| 2500 static int codeEqualityTerm( | |
| 2501 Parse *pParse, /* The parsing context */ | |
| 2502 WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ | |
| 2503 WhereLevel *pLevel, /* The level of the FROM clause we are working on */ | |
| 2504 int iEq, /* Index of the equality term within this level */ | |
| 2505 int bRev, /* True for reverse-order IN operations */ | |
| 2506 int iTarget /* Attempt to leave results in this register */ | |
| 2507 ){ | |
| 2508 Expr *pX = pTerm->pExpr; | |
| 2509 Vdbe *v = pParse->pVdbe; | |
| 2510 int iReg; /* Register holding results */ | |
| 2511 | |
| 2512 assert( iTarget>0 ); | |
| 2513 if( pX->op==TK_EQ ){ | |
| 2514 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); | |
| 2515 }else if( pX->op==TK_ISNULL ){ | |
| 2516 iReg = iTarget; | |
| 2517 sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); | |
| 2518 #ifndef SQLITE_OMIT_SUBQUERY | |
| 2519 }else{ | |
| 2520 int eType; | |
| 2521 int iTab; | |
| 2522 struct InLoop *pIn; | |
| 2523 WhereLoop *pLoop = pLevel->pWLoop; | |
| 2524 | |
| 2525 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 | |
| 2526 && pLoop->u.btree.pIndex!=0 | |
| 2527 && pLoop->u.btree.pIndex->aSortOrder[iEq] | |
| 2528 ){ | |
| 2529 testcase( iEq==0 ); | |
| 2530 testcase( bRev ); | |
| 2531 bRev = !bRev; | |
| 2532 } | |
| 2533 assert( pX->op==TK_IN ); | |
| 2534 iReg = iTarget; | |
| 2535 eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0); | |
| 2536 if( eType==IN_INDEX_INDEX_DESC ){ | |
| 2537 testcase( bRev ); | |
| 2538 bRev = !bRev; | |
| 2539 } | |
| 2540 iTab = pX->iTable; | |
| 2541 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0); | |
| 2542 VdbeCoverageIf(v, bRev); | |
| 2543 VdbeCoverageIf(v, !bRev); | |
| 2544 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 ); | |
| 2545 pLoop->wsFlags |= WHERE_IN_ABLE; | |
| 2546 if( pLevel->u.in.nIn==0 ){ | |
| 2547 pLevel->addrNxt = sqlite3VdbeMakeLabel(v); | |
| 2548 } | |
| 2549 pLevel->u.in.nIn++; | |
| 2550 pLevel->u.in.aInLoop = | |
| 2551 sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop, | |
| 2552 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn); | |
| 2553 pIn = pLevel->u.in.aInLoop; | |
| 2554 if( pIn ){ | |
| 2555 pIn += pLevel->u.in.nIn - 1; | |
| 2556 pIn->iCur = iTab; | |
| 2557 if( eType==IN_INDEX_ROWID ){ | |
| 2558 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); | |
| 2559 }else{ | |
| 2560 pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg); | |
| 2561 } | |
| 2562 pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen; | |
| 2563 sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v); | |
| 2564 }else{ | |
| 2565 pLevel->u.in.nIn = 0; | |
| 2566 } | |
| 2567 #endif | |
| 2568 } | |
| 2569 disableTerm(pLevel, pTerm); | |
| 2570 return iReg; | |
| 2571 } | |
| 2572 | |
| 2573 /* | |
| 2574 ** Generate code that will evaluate all == and IN constraints for an | |
| 2575 ** index scan. | |
| 2576 ** | |
| 2577 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c). | |
| 2578 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10 | |
| 2579 ** The index has as many as three equality constraints, but in this | |
| 2580 ** example, the third "c" value is an inequality. So only two | |
| 2581 ** constraints are coded. This routine will generate code to evaluate | |
| 2582 ** a==5 and b IN (1,2,3). The current values for a and b will be stored | |
| 2583 ** in consecutive registers and the index of the first register is returned. | |
| 2584 ** | |
| 2585 ** In the example above nEq==2. But this subroutine works for any value | |
| 2586 ** of nEq including 0. If nEq==0, this routine is nearly a no-op. | |
| 2587 ** The only thing it does is allocate the pLevel->iMem memory cell and | |
| 2588 ** compute the affinity string. | |
| 2589 ** | |
| 2590 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints | |
| 2591 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is | |
| 2592 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that | |
| 2593 ** occurs after the nEq quality constraints. | |
| 2594 ** | |
| 2595 ** This routine allocates a range of nEq+nExtraReg memory cells and returns | |
| 2596 ** the index of the first memory cell in that range. The code that | |
| 2597 ** calls this routine will use that memory range to store keys for | |
| 2598 ** start and termination conditions of the loop. | |
| 2599 ** key value of the loop. If one or more IN operators appear, then | |
| 2600 ** this routine allocates an additional nEq memory cells for internal | |
| 2601 ** use. | |
| 2602 ** | |
| 2603 ** Before returning, *pzAff is set to point to a buffer containing a | |
| 2604 ** copy of the column affinity string of the index allocated using | |
| 2605 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated | |
| 2606 ** with equality constraints that use NONE affinity are set to | |
| 2607 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following: | |
| 2608 ** | |
| 2609 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b); | |
| 2610 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b; | |
| 2611 ** | |
| 2612 ** In the example above, the index on t1(a) has TEXT affinity. But since | |
| 2613 ** the right hand side of the equality constraint (t2.b) has NONE affinity, | |
| 2614 ** no conversion should be attempted before using a t2.b value as part of | |
| 2615 ** a key to search the index. Hence the first byte in the returned affinity | |
| 2616 ** string in this example would be set to SQLITE_AFF_NONE. | |
| 2617 */ | |
| 2618 static int codeAllEqualityTerms( | |
| 2619 Parse *pParse, /* Parsing context */ | |
| 2620 WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ | |
| 2621 int bRev, /* Reverse the order of IN operators */ | |
| 2622 int nExtraReg, /* Number of extra registers to allocate */ | |
| 2623 char **pzAff /* OUT: Set to point to affinity string */ | |
| 2624 ){ | |
| 2625 u16 nEq; /* The number of == or IN constraints to code */ | |
| 2626 u16 nSkip; /* Number of left-most columns to skip */ | |
| 2627 Vdbe *v = pParse->pVdbe; /* The vm under construction */ | |
| 2628 Index *pIdx; /* The index being used for this loop */ | |
| 2629 WhereTerm *pTerm; /* A single constraint term */ | |
| 2630 WhereLoop *pLoop; /* The WhereLoop object */ | |
| 2631 int j; /* Loop counter */ | |
| 2632 int regBase; /* Base register */ | |
| 2633 int nReg; /* Number of registers to allocate */ | |
| 2634 char *zAff; /* Affinity string to return */ | |
| 2635 | |
| 2636 /* This module is only called on query plans that use an index. */ | |
| 2637 pLoop = pLevel->pWLoop; | |
| 2638 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ); | |
| 2639 nEq = pLoop->u.btree.nEq; | |
| 2640 nSkip = pLoop->u.btree.nSkip; | |
| 2641 pIdx = pLoop->u.btree.pIndex; | |
| 2642 assert( pIdx!=0 ); | |
| 2643 | |
| 2644 /* Figure out how many memory cells we will need then allocate them. | |
| 2645 */ | |
| 2646 regBase = pParse->nMem + 1; | |
| 2647 nReg = pLoop->u.btree.nEq + nExtraReg; | |
| 2648 pParse->nMem += nReg; | |
| 2649 | |
| 2650 zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx)); | |
| 2651 if( !zAff ){ | |
| 2652 pParse->db->mallocFailed = 1; | |
| 2653 } | |
| 2654 | |
| 2655 if( nSkip ){ | |
| 2656 int iIdxCur = pLevel->iIdxCur; | |
| 2657 sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur); | |
| 2658 VdbeCoverageIf(v, bRev==0); | |
| 2659 VdbeCoverageIf(v, bRev!=0); | |
| 2660 VdbeComment((v, "begin skip-scan on %s", pIdx->zName)); | |
| 2661 j = sqlite3VdbeAddOp0(v, OP_Goto); | |
| 2662 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT), | |
| 2663 iIdxCur, 0, regBase, nSkip); | |
| 2664 VdbeCoverageIf(v, bRev==0); | |
| 2665 VdbeCoverageIf(v, bRev!=0); | |
| 2666 sqlite3VdbeJumpHere(v, j); | |
| 2667 for(j=0; j<nSkip; j++){ | |
| 2668 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j); | |
| 2669 assert( pIdx->aiColumn[j]>=0 ); | |
| 2670 VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName)); | |
| 2671 } | |
| 2672 } | |
| 2673 | |
| 2674 /* Evaluate the equality constraints | |
| 2675 */ | |
| 2676 assert( zAff==0 || (int)strlen(zAff)>=nEq ); | |
| 2677 for(j=nSkip; j<nEq; j++){ | |
| 2678 int r1; | |
| 2679 pTerm = pLoop->aLTerm[j]; | |
| 2680 assert( pTerm!=0 ); | |
| 2681 /* The following testcase is true for indices with redundant columns. | |
| 2682 ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */ | |
| 2683 testcase( (pTerm->wtFlags & TERM_CODED)!=0 ); | |
| 2684 testcase( pTerm->wtFlags & TERM_VIRTUAL ); | |
| 2685 r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j); | |
| 2686 if( r1!=regBase+j ){ | |
| 2687 if( nReg==1 ){ | |
| 2688 sqlite3ReleaseTempReg(pParse, regBase); | |
| 2689 regBase = r1; | |
| 2690 }else{ | |
| 2691 sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); | |
| 2692 } | |
| 2693 } | |
| 2694 testcase( pTerm->eOperator & WO_ISNULL ); | |
| 2695 testcase( pTerm->eOperator & WO_IN ); | |
| 2696 if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ | |
| 2697 Expr *pRight = pTerm->pExpr->pRight; | |
| 2698 if( sqlite3ExprCanBeNull(pRight) ){ | |
| 2699 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk); | |
| 2700 VdbeCoverage(v); | |
| 2701 } | |
| 2702 if( zAff ){ | |
| 2703 if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){ | |
| 2704 zAff[j] = SQLITE_AFF_NONE; | |
| 2705 } | |
| 2706 if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){ | |
| 2707 zAff[j] = SQLITE_AFF_NONE; | |
| 2708 } | |
| 2709 } | |
| 2710 } | |
| 2711 } | |
| 2712 *pzAff = zAff; | |
| 2713 return regBase; | |
| 2714 } | |
| 2715 | |
| 2716 #ifndef SQLITE_OMIT_EXPLAIN | |
| 2717 /* | |
| 2718 ** This routine is a helper for explainIndexRange() below | |
| 2719 ** | |
| 2720 ** pStr holds the text of an expression that we are building up one term | |
| 2721 ** at a time. This routine adds a new term to the end of the expression. | |
| 2722 ** Terms are separated by AND so add the "AND" text for second and subsequent | |
| 2723 ** terms only. | |
| 2724 */ | |
| 2725 static void explainAppendTerm( | |
| 2726 StrAccum *pStr, /* The text expression being built */ | |
| 2727 int iTerm, /* Index of this term. First is zero */ | |
| 2728 const char *zColumn, /* Name of the column */ | |
| 2729 const char *zOp /* Name of the operator */ | |
| 2730 ){ | |
| 2731 if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5); | |
| 2732 sqlite3StrAccumAppendAll(pStr, zColumn); | |
| 2733 sqlite3StrAccumAppend(pStr, zOp, 1); | |
| 2734 sqlite3StrAccumAppend(pStr, "?", 1); | |
| 2735 } | |
| 2736 | |
| 2737 /* | |
| 2738 ** Argument pLevel describes a strategy for scanning table pTab. This | |
| 2739 ** function appends text to pStr that describes the subset of table | |
| 2740 ** rows scanned by the strategy in the form of an SQL expression. | |
| 2741 ** | |
| 2742 ** For example, if the query: | |
| 2743 ** | |
| 2744 ** SELECT * FROM t1 WHERE a=1 AND b>2; | |
| 2745 ** | |
| 2746 ** is run and there is an index on (a, b), then this function returns a | |
| 2747 ** string similar to: | |
| 2748 ** | |
| 2749 ** "a=? AND b>?" | |
| 2750 */ | |
| 2751 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){ | |
| 2752 Index *pIndex = pLoop->u.btree.pIndex; | |
| 2753 u16 nEq = pLoop->u.btree.nEq; | |
| 2754 u16 nSkip = pLoop->u.btree.nSkip; | |
| 2755 int i, j; | |
| 2756 Column *aCol = pTab->aCol; | |
| 2757 i16 *aiColumn = pIndex->aiColumn; | |
| 2758 | |
| 2759 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return; | |
| 2760 sqlite3StrAccumAppend(pStr, " (", 2); | |
| 2761 for(i=0; i<nEq; i++){ | |
| 2762 char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName; | |
| 2763 if( i>=nSkip ){ | |
| 2764 explainAppendTerm(pStr, i, z, "="); | |
| 2765 }else{ | |
| 2766 if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5); | |
| 2767 sqlite3XPrintf(pStr, 0, "ANY(%s)", z); | |
| 2768 } | |
| 2769 } | |
| 2770 | |
| 2771 j = i; | |
| 2772 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){ | |
| 2773 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName; | |
| 2774 explainAppendTerm(pStr, i++, z, ">"); | |
| 2775 } | |
| 2776 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){ | |
| 2777 char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName; | |
| 2778 explainAppendTerm(pStr, i, z, "<"); | |
| 2779 } | |
| 2780 sqlite3StrAccumAppend(pStr, ")", 1); | |
| 2781 } | |
| 2782 | |
| 2783 /* | |
| 2784 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN | |
| 2785 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single | |
| 2786 ** record is added to the output to describe the table scan strategy in | |
| 2787 ** pLevel. | |
| 2788 */ | |
| 2789 static void explainOneScan( | |
| 2790 Parse *pParse, /* Parse context */ | |
| 2791 SrcList *pTabList, /* Table list this loop refers to */ | |
| 2792 WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */ | |
| 2793 int iLevel, /* Value for "level" column of output */ | |
| 2794 int iFrom, /* Value for "from" column of output */ | |
| 2795 u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */ | |
| 2796 ){ | |
| 2797 #ifndef SQLITE_DEBUG | |
| 2798 if( pParse->explain==2 ) | |
| 2799 #endif | |
| 2800 { | |
| 2801 struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom]; | |
| 2802 Vdbe *v = pParse->pVdbe; /* VM being constructed */ | |
| 2803 sqlite3 *db = pParse->db; /* Database handle */ | |
| 2804 int iId = pParse->iSelectId; /* Select id (left-most output column) */ | |
| 2805 int isSearch; /* True for a SEARCH. False for SCAN. */ | |
| 2806 WhereLoop *pLoop; /* The controlling WhereLoop object */ | |
| 2807 u32 flags; /* Flags that describe this loop */ | |
| 2808 char *zMsg; /* Text to add to EQP output */ | |
| 2809 StrAccum str; /* EQP output string */ | |
| 2810 char zBuf[100]; /* Initial space for EQP output string */ | |
| 2811 | |
| 2812 pLoop = pLevel->pWLoop; | |
| 2813 flags = pLoop->wsFlags; | |
| 2814 if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return; | |
| 2815 | |
| 2816 isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 | |
| 2817 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0)) | |
| 2818 || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX)); | |
| 2819 | |
| 2820 sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH); | |
| 2821 str.db = db; | |
| 2822 sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN"); | |
| 2823 if( pItem->pSelect ){ | |
| 2824 sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId); | |
| 2825 }else{ | |
| 2826 sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName); | |
| 2827 } | |
| 2828 | |
| 2829 if( pItem->zAlias ){ | |
| 2830 sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias); | |
| 2831 } | |
| 2832 if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){ | |
| 2833 const char *zFmt = 0; | |
| 2834 Index *pIdx; | |
| 2835 | |
| 2836 assert( pLoop->u.btree.pIndex!=0 ); | |
| 2837 pIdx = pLoop->u.btree.pIndex; | |
| 2838 assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) ); | |
| 2839 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){ | |
| 2840 if( isSearch ){ | |
| 2841 zFmt = "PRIMARY KEY"; | |
| 2842 } | |
| 2843 }else if( flags & WHERE_AUTO_INDEX ){ | |
| 2844 zFmt = "AUTOMATIC COVERING INDEX"; | |
| 2845 }else if( flags & WHERE_IDX_ONLY ){ | |
| 2846 zFmt = "COVERING INDEX %s"; | |
| 2847 }else{ | |
| 2848 zFmt = "INDEX %s"; | |
| 2849 } | |
| 2850 if( zFmt ){ | |
| 2851 sqlite3StrAccumAppend(&str, " USING ", 7); | |
| 2852 sqlite3XPrintf(&str, 0, zFmt, pIdx->zName); | |
| 2853 explainIndexRange(&str, pLoop, pItem->pTab); | |
| 2854 } | |
| 2855 }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){ | |
| 2856 const char *zRange; | |
| 2857 if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){ | |
| 2858 zRange = "(rowid=?)"; | |
| 2859 }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){ | |
| 2860 zRange = "(rowid>? AND rowid<?)"; | |
| 2861 }else if( flags&WHERE_BTM_LIMIT ){ | |
| 2862 zRange = "(rowid>?)"; | |
| 2863 }else{ | |
| 2864 assert( flags&WHERE_TOP_LIMIT); | |
| 2865 zRange = "(rowid<?)"; | |
| 2866 } | |
| 2867 sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY "); | |
| 2868 sqlite3StrAccumAppendAll(&str, zRange); | |
| 2869 } | |
| 2870 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 2871 else if( (flags & WHERE_VIRTUALTABLE)!=0 ){ | |
| 2872 sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s", | |
| 2873 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr); | |
| 2874 } | |
| 2875 #endif | |
| 2876 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS | |
| 2877 if( pLoop->nOut>=10 ){ | |
| 2878 sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut)); | |
| 2879 }else{ | |
| 2880 sqlite3StrAccumAppend(&str, " (~1 row)", 9); | |
| 2881 } | |
| 2882 #endif | |
| 2883 zMsg = sqlite3StrAccumFinish(&str); | |
| 2884 sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC); | |
| 2885 } | |
| 2886 } | |
| 2887 #else | |
| 2888 # define explainOneScan(u,v,w,x,y,z) | |
| 2889 #endif /* SQLITE_OMIT_EXPLAIN */ | |
| 2890 | |
| 2891 | |
| 2892 /* | |
| 2893 ** Generate code for the start of the iLevel-th loop in the WHERE clause | |
| 2894 ** implementation described by pWInfo. | |
| 2895 */ | |
| 2896 static Bitmask codeOneLoopStart( | |
| 2897 WhereInfo *pWInfo, /* Complete information about the WHERE clause */ | |
| 2898 int iLevel, /* Which level of pWInfo->a[] should be coded */ | |
| 2899 Bitmask notReady /* Which tables are currently available */ | |
| 2900 ){ | |
| 2901 int j, k; /* Loop counters */ | |
| 2902 int iCur; /* The VDBE cursor for the table */ | |
| 2903 int addrNxt; /* Where to jump to continue with the next IN case */ | |
| 2904 int omitTable; /* True if we use the index only */ | |
| 2905 int bRev; /* True if we need to scan in reverse order */ | |
| 2906 WhereLevel *pLevel; /* The where level to be coded */ | |
| 2907 WhereLoop *pLoop; /* The WhereLoop object being coded */ | |
| 2908 WhereClause *pWC; /* Decomposition of the entire WHERE clause */ | |
| 2909 WhereTerm *pTerm; /* A WHERE clause term */ | |
| 2910 Parse *pParse; /* Parsing context */ | |
| 2911 sqlite3 *db; /* Database connection */ | |
| 2912 Vdbe *v; /* The prepared stmt under constructions */ | |
| 2913 struct SrcList_item *pTabItem; /* FROM clause term being coded */ | |
| 2914 int addrBrk; /* Jump here to break out of the loop */ | |
| 2915 int addrCont; /* Jump here to continue with next cycle */ | |
| 2916 int iRowidReg = 0; /* Rowid is stored in this register, if not zero */ | |
| 2917 int iReleaseReg = 0; /* Temp register to free before returning */ | |
| 2918 | |
| 2919 pParse = pWInfo->pParse; | |
| 2920 v = pParse->pVdbe; | |
| 2921 pWC = &pWInfo->sWC; | |
| 2922 db = pParse->db; | |
| 2923 pLevel = &pWInfo->a[iLevel]; | |
| 2924 pLoop = pLevel->pWLoop; | |
| 2925 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom]; | |
| 2926 iCur = pTabItem->iCursor; | |
| 2927 pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur); | |
| 2928 bRev = (pWInfo->revMask>>iLevel)&1; | |
| 2929 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 | |
| 2930 && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0; | |
| 2931 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName)); | |
| 2932 | |
| 2933 /* Create labels for the "break" and "continue" instructions | |
| 2934 ** for the current loop. Jump to addrBrk to break out of a loop. | |
| 2935 ** Jump to cont to go immediately to the next iteration of the | |
| 2936 ** loop. | |
| 2937 ** | |
| 2938 ** When there is an IN operator, we also have a "addrNxt" label that | |
| 2939 ** means to continue with the next IN value combination. When | |
| 2940 ** there are no IN operators in the constraints, the "addrNxt" label | |
| 2941 ** is the same as "addrBrk". | |
| 2942 */ | |
| 2943 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v); | |
| 2944 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v); | |
| 2945 | |
| 2946 /* If this is the right table of a LEFT OUTER JOIN, allocate and | |
| 2947 ** initialize a memory cell that records if this table matches any | |
| 2948 ** row of the left table of the join. | |
| 2949 */ | |
| 2950 if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){ | |
| 2951 pLevel->iLeftJoin = ++pParse->nMem; | |
| 2952 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); | |
| 2953 VdbeComment((v, "init LEFT JOIN no-match flag")); | |
| 2954 } | |
| 2955 | |
| 2956 /* Special case of a FROM clause subquery implemented as a co-routine */ | |
| 2957 if( pTabItem->viaCoroutine ){ | |
| 2958 int regYield = pTabItem->regReturn; | |
| 2959 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub); | |
| 2960 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk); | |
| 2961 VdbeCoverage(v); | |
| 2962 VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName)); | |
| 2963 pLevel->op = OP_Goto; | |
| 2964 }else | |
| 2965 | |
| 2966 #ifndef SQLITE_OMIT_VIRTUALTABLE | |
| 2967 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ | |
| 2968 /* Case 1: The table is a virtual-table. Use the VFilter and VNext | |
| 2969 ** to access the data. | |
| 2970 */ | |
| 2971 int iReg; /* P3 Value for OP_VFilter */ | |
| 2972 int addrNotFound; | |
| 2973 int nConstraint = pLoop->nLTerm; | |
| 2974 | |
| 2975 sqlite3ExprCachePush(pParse); | |
| 2976 iReg = sqlite3GetTempRange(pParse, nConstraint+2); | |
| 2977 addrNotFound = pLevel->addrBrk; | |
| 2978 for(j=0; j<nConstraint; j++){ | |
| 2979 int iTarget = iReg+j+2; | |
| 2980 pTerm = pLoop->aLTerm[j]; | |
| 2981 if( pTerm==0 ) continue; | |
| 2982 if( pTerm->eOperator & WO_IN ){ | |
| 2983 codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget); | |
| 2984 addrNotFound = pLevel->addrNxt; | |
| 2985 }else{ | |
| 2986 sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget); | |
| 2987 } | |
| 2988 } | |
| 2989 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg); | |
| 2990 sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1); | |
| 2991 sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, | |
| 2992 pLoop->u.vtab.idxStr, | |
| 2993 pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC); | |
| 2994 VdbeCoverage(v); | |
| 2995 pLoop->u.vtab.needFree = 0; | |
| 2996 for(j=0; j<nConstraint && j<16; j++){ | |
| 2997 if( (pLoop->u.vtab.omitMask>>j)&1 ){ | |
| 2998 disableTerm(pLevel, pLoop->aLTerm[j]); | |
| 2999 } | |
| 3000 } | |
| 3001 pLevel->op = OP_VNext; | |
| 3002 pLevel->p1 = iCur; | |
| 3003 pLevel->p2 = sqlite3VdbeCurrentAddr(v); | |
| 3004 sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); | |
| 3005 sqlite3ExprCachePop(pParse); | |
| 3006 }else | |
| 3007 #endif /* SQLITE_OMIT_VIRTUALTABLE */ | |
| 3008 | |
| 3009 if( (pLoop->wsFlags & WHERE_IPK)!=0 | |
| 3010 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0 | |
| 3011 ){ | |
| 3012 /* Case 2: We can directly reference a single row using an | |
| 3013 ** equality comparison against the ROWID field. Or | |
| 3014 ** we reference multiple rows using a "rowid IN (...)" | |
| 3015 ** construct. | |
| 3016 */ | |
| 3017 assert( pLoop->u.btree.nEq==1 ); | |
| 3018 pTerm = pLoop->aLTerm[0]; | |
| 3019 assert( pTerm!=0 ); | |
| 3020 assert( pTerm->pExpr!=0 ); | |
| 3021 assert( omitTable==0 ); | |
| 3022 testcase( pTerm->wtFlags & TERM_VIRTUAL ); | |
| 3023 iReleaseReg = ++pParse->nMem; | |
| 3024 iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg); | |
| 3025 if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg); | |
| 3026 addrNxt = pLevel->addrNxt; | |
| 3027 sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v); | |
| 3028 sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg); | |
| 3029 VdbeCoverage(v); | |
| 3030 sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1); | |
| 3031 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); | |
| 3032 VdbeComment((v, "pk")); | |
| 3033 pLevel->op = OP_Noop; | |
| 3034 }else if( (pLoop->wsFlags & WHERE_IPK)!=0 | |
| 3035 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0 | |
| 3036 ){ | |
| 3037 /* Case 3: We have an inequality comparison against the ROWID field. | |
| 3038 */ | |
| 3039 int testOp = OP_Noop; | |
| 3040 int start; | |
| 3041 int memEndValue = 0; | |
| 3042 WhereTerm *pStart, *pEnd; | |
| 3043 | |
| 3044 assert( omitTable==0 ); | |
| 3045 j = 0; | |
| 3046 pStart = pEnd = 0; | |
| 3047 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++]; | |
| 3048 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++]; | |
| 3049 assert( pStart!=0 || pEnd!=0 ); | |
| 3050 if( bRev ){ | |
| 3051 pTerm = pStart; | |
| 3052 pStart = pEnd; | |
| 3053 pEnd = pTerm; | |
| 3054 } | |
| 3055 if( pStart ){ | |
| 3056 Expr *pX; /* The expression that defines the start bound */ | |
| 3057 int r1, rTemp; /* Registers for holding the start boundary */ | |
| 3058 | |
| 3059 /* The following constant maps TK_xx codes into corresponding | |
| 3060 ** seek opcodes. It depends on a particular ordering of TK_xx | |
| 3061 */ | |
| 3062 const u8 aMoveOp[] = { | |
| 3063 /* TK_GT */ OP_SeekGT, | |
| 3064 /* TK_LE */ OP_SeekLE, | |
| 3065 /* TK_LT */ OP_SeekLT, | |
| 3066 /* TK_GE */ OP_SeekGE | |
| 3067 }; | |
| 3068 assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */ | |
| 3069 assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */ | |
| 3070 assert( TK_GE==TK_GT+3 ); /* ... is correcct. */ | |
| 3071 | |
| 3072 assert( (pStart->wtFlags & TERM_VNULL)==0 ); | |
| 3073 testcase( pStart->wtFlags & TERM_VIRTUAL ); | |
| 3074 pX = pStart->pExpr; | |
| 3075 assert( pX!=0 ); | |
| 3076 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */ | |
| 3077 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp); | |
| 3078 sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1); | |
| 3079 VdbeComment((v, "pk")); | |
| 3080 VdbeCoverageIf(v, pX->op==TK_GT); | |
| 3081 VdbeCoverageIf(v, pX->op==TK_LE); | |
| 3082 VdbeCoverageIf(v, pX->op==TK_LT); | |
| 3083 VdbeCoverageIf(v, pX->op==TK_GE); | |
| 3084 sqlite3ExprCacheAffinityChange(pParse, r1, 1); | |
| 3085 sqlite3ReleaseTempReg(pParse, rTemp); | |
| 3086 disableTerm(pLevel, pStart); | |
| 3087 }else{ | |
| 3088 sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk); | |
| 3089 VdbeCoverageIf(v, bRev==0); | |
| 3090 VdbeCoverageIf(v, bRev!=0); | |
| 3091 } | |
| 3092 if( pEnd ){ | |
| 3093 Expr *pX; | |
| 3094 pX = pEnd->pExpr; | |
| 3095 assert( pX!=0 ); | |
| 3096 assert( (pEnd->wtFlags & TERM_VNULL)==0 ); | |
| 3097 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */ | |
| 3098 testcase( pEnd->wtFlags & TERM_VIRTUAL ); | |
| 3099 memEndValue = ++pParse->nMem; | |
| 3100 sqlite3ExprCode(pParse, pX->pRight, memEndValue); | |
| 3101 if( pX->op==TK_LT || pX->op==TK_GT ){ | |
| 3102 testOp = bRev ? OP_Le : OP_Ge; | |
| 3103 }else{ | |
| 3104 testOp = bRev ? OP_Lt : OP_Gt; | |
| 3105 } | |
| 3106 disableTerm(pLevel, pEnd); | |
| 3107 } | |
| 3108 start = sqlite3VdbeCurrentAddr(v); | |
| 3109 pLevel->op = bRev ? OP_Prev : OP_Next; | |
| 3110 pLevel->p1 = iCur; | |
| 3111 pLevel->p2 = start; | |
| 3112 assert( pLevel->p5==0 ); | |
| 3113 if( testOp!=OP_Noop ){ | |
| 3114 iRowidReg = ++pParse->nMem; | |
| 3115 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg); | |
| 3116 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); | |
| 3117 sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg); | |
| 3118 VdbeCoverageIf(v, testOp==OP_Le); | |
| 3119 VdbeCoverageIf(v, testOp==OP_Lt); | |
| 3120 VdbeCoverageIf(v, testOp==OP_Ge); | |
| 3121 VdbeCoverageIf(v, testOp==OP_Gt); | |
| 3122 sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); | |
| 3123 } | |
| 3124 }else if( pLoop->wsFlags & WHERE_INDEXED ){ | |
| 3125 /* Case 4: A scan using an index. | |
| 3126 ** | |
| 3127 ** The WHERE clause may contain zero or more equality | |
| 3128 ** terms ("==" or "IN" operators) that refer to the N | |
| 3129 ** left-most columns of the index. It may also contain | |
| 3130 ** inequality constraints (>, <, >= or <=) on the indexed | |
| 3131 ** column that immediately follows the N equalities. Only | |
| 3132 ** the right-most column can be an inequality - the rest must | |
| 3133 ** use the "==" and "IN" operators. For example, if the | |
| 3134 ** index is on (x,y,z), then the following clauses are all | |
| 3135 ** optimized: | |
| 3136 ** | |
| 3137 ** x=5 | |
| 3138 ** x=5 AND y=10 | |
| 3139 ** x=5 AND y<10 | |
| 3140 ** x=5 AND y>5 AND y<10 | |
| 3141 ** x=5 AND y=5 AND z<=10 | |
| 3142 ** | |
| 3143 ** The z<10 term of the following cannot be used, only | |
| 3144 ** the x=5 term: | |
| 3145 ** | |
| 3146 ** x=5 AND z<10 | |
| 3147 ** | |
| 3148 ** N may be zero if there are inequality constraints. | |
| 3149 ** If there are no inequality constraints, then N is at | |
| 3150 ** least one. | |
| 3151 ** | |
| 3152 ** This case is also used when there are no WHERE clause | |
| 3153 ** constraints but an index is selected anyway, in order | |
| 3154 ** to force the output order to conform to an ORDER BY. | |
| 3155 */ | |
| 3156 static const u8 aStartOp[] = { | |
| 3157 0, | |
| 3158 0, | |
| 3159 OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ | |
| 3160 OP_Last, /* 3: (!start_constraints && startEq && bRev) */ | |
| 3161 OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */ | |
| 3162 OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */ | |
| 3163 OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */ | |
| 3164 OP_SeekLE /* 7: (start_constraints && startEq && bRev) */ | |
| 3165 }; | |
| 3166 static const u8 aEndOp[] = { | |
| 3167 OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */ | |
| 3168 OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */ | |
| 3169 OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */ | |
| 3170 OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */ | |
| 3171 }; | |
| 3172 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */ | |
| 3173 int regBase; /* Base register holding constraint values */ | |
| 3174 WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ | |
| 3175 WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ | |
| 3176 int startEq; /* True if range start uses ==, >= or <= */ | |
| 3177 int endEq; /* True if range end uses ==, >= or <= */ | |
| 3178 int start_constraints; /* Start of range is constrained */ | |
| 3179 int nConstraint; /* Number of constraint terms */ | |
| 3180 Index *pIdx; /* The index we will be using */ | |
| 3181 int iIdxCur; /* The VDBE cursor for the index */ | |
| 3182 int nExtraReg = 0; /* Number of extra registers needed */ | |
| 3183 int op; /* Instruction opcode */ | |
| 3184 char *zStartAff; /* Affinity for start of range constraint */ | |
| 3185 char cEndAff = 0; /* Affinity for end of range constraint */ | |
| 3186 u8 bSeekPastNull = 0; /* True to seek past initial nulls */ | |
| 3187 u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */ | |
| 3188 | |
| 3189 pIdx = pLoop->u.btree.pIndex; | |
| 3190 iIdxCur = pLevel->iIdxCur; | |
| 3191 assert( nEq>=pLoop->u.btree.nSkip ); | |
| 3192 | |
| 3193 /* If this loop satisfies a sort order (pOrderBy) request that | |
| 3194 ** was passed to this function to implement a "SELECT min(x) ..." | |
| 3195 ** query, then the caller will only allow the loop to run for | |
| 3196 ** a single iteration. This means that the first row returned | |
| 3197 ** should not have a NULL value stored in 'x'. If column 'x' is | |
| 3198 ** the first one after the nEq equality constraints in the index, | |
| 3199 ** this requires some special handling. | |
| 3200 */ | |
| 3201 assert( pWInfo->pOrderBy==0 | |
| 3202 || pWInfo->pOrderBy->nExpr==1 | |
| 3203 || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 ); | |
| 3204 if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0 | |
| 3205 && pWInfo->nOBSat>0 | |
| 3206 && (pIdx->nKeyCol>nEq) | |
| 3207 ){ | |
| 3208 assert( pLoop->u.btree.nSkip==0 ); | |
| 3209 bSeekPastNull = 1; | |
| 3210 nExtraReg = 1; | |
| 3211 } | |
| 3212 | |
| 3213 /* Find any inequality constraint terms for the start and end | |
| 3214 ** of the range. | |
| 3215 */ | |
| 3216 j = nEq; | |
| 3217 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){ | |
| 3218 pRangeStart = pLoop->aLTerm[j++]; | |
| 3219 nExtraReg = 1; | |
| 3220 } | |
| 3221 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){ | |
| 3222 pRangeEnd = pLoop->aLTerm[j++]; | |
| 3223 nExtraReg = 1; | |
| 3224 if( pRangeStart==0 | |
| 3225 && (j = pIdx->aiColumn[nEq])>=0 | |
| 3226 && pIdx->pTable->aCol[j].notNull==0 | |
| 3227 ){ | |
| 3228 bSeekPastNull = 1; | |
| 3229 } | |
| 3230 } | |
| 3231 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 ); | |
| 3232 | |
| 3233 /* Generate code to evaluate all constraint terms using == or IN | |
| 3234 ** and store the values of those terms in an array of registers | |
| 3235 ** starting at regBase. | |
| 3236 */ | |
| 3237 regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff); | |
| 3238 assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq ); | |
| 3239 if( zStartAff ) cEndAff = zStartAff[nEq]; | |
| 3240 addrNxt = pLevel->addrNxt; | |
| 3241 | |
| 3242 /* If we are doing a reverse order scan on an ascending index, or | |
| 3243 ** a forward order scan on a descending index, interchange the | |
| 3244 ** start and end terms (pRangeStart and pRangeEnd). | |
| 3245 */ | |
| 3246 if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) | |
| 3247 || (bRev && pIdx->nKeyCol==nEq) | |
| 3248 ){ | |
| 3249 SWAP(WhereTerm *, pRangeEnd, pRangeStart); | |
| 3250 SWAP(u8, bSeekPastNull, bStopAtNull); | |
| 3251 } | |
| 3252 | |
| 3253 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 ); | |
| 3254 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 ); | |
| 3255 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 ); | |
| 3256 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 ); | |
| 3257 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); | |
| 3258 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); | |
| 3259 start_constraints = pRangeStart || nEq>0; | |
| 3260 | |
| 3261 /* Seek the index cursor to the start of the range. */ | |
| 3262 nConstraint = nEq; | |
| 3263 if( pRangeStart ){ | |
| 3264 Expr *pRight = pRangeStart->pExpr->pRight; | |
| 3265 sqlite3ExprCode(pParse, pRight, regBase+nEq); | |
| 3266 if( (pRangeStart->wtFlags & TERM_VNULL)==0 | |
| 3267 && sqlite3ExprCanBeNull(pRight) | |
| 3268 ){ | |
| 3269 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); | |
| 3270 VdbeCoverage(v); | |
| 3271 } | |
| 3272 if( zStartAff ){ | |
| 3273 if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){ | |
| 3274 /* Since the comparison is to be performed with no conversions | |
| 3275 ** applied to the operands, set the affinity to apply to pRight to | |
| 3276 ** SQLITE_AFF_NONE. */ | |
| 3277 zStartAff[nEq] = SQLITE_AFF_NONE; | |
| 3278 } | |
| 3279 if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){ | |
| 3280 zStartAff[nEq] = SQLITE_AFF_NONE; | |
| 3281 } | |
| 3282 } | |
| 3283 nConstraint++; | |
| 3284 testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); | |
| 3285 }else if( bSeekPastNull ){ | |
| 3286 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); | |
| 3287 nConstraint++; | |
| 3288 startEq = 0; | |
| 3289 start_constraints = 1; | |
| 3290 } | |
| 3291 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff); | |
| 3292 op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; | |
| 3293 assert( op!=0 ); | |
| 3294 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); | |
| 3295 VdbeCoverage(v); | |
| 3296 VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind ); | |
| 3297 VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last ); | |
| 3298 VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT ); | |
| 3299 VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE ); | |
| 3300 VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE ); | |
| 3301 VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT ); | |
| 3302 | |
| 3303 /* Load the value for the inequality constraint at the end of the | |
| 3304 ** range (if any). | |
| 3305 */ | |
| 3306 nConstraint = nEq; | |
| 3307 if( pRangeEnd ){ | |
| 3308 Expr *pRight = pRangeEnd->pExpr->pRight; | |
| 3309 sqlite3ExprCacheRemove(pParse, regBase+nEq, 1); | |
| 3310 sqlite3ExprCode(pParse, pRight, regBase+nEq); | |
| 3311 if( (pRangeEnd->wtFlags & TERM_VNULL)==0 | |
| 3312 && sqlite3ExprCanBeNull(pRight) | |
| 3313 ){ | |
| 3314 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt); | |
| 3315 VdbeCoverage(v); | |
| 3316 } | |
| 3317 if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE | |
| 3318 && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff) | |
| 3319 ){ | |
| 3320 codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff); | |
| 3321 } | |
| 3322 nConstraint++; | |
| 3323 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); | |
| 3324 }else if( bStopAtNull ){ | |
| 3325 sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); | |
| 3326 endEq = 0; | |
| 3327 nConstraint++; | |
| 3328 } | |
| 3329 sqlite3DbFree(db, zStartAff); | |
| 3330 | |
| 3331 /* Top of the loop body */ | |
| 3332 pLevel->p2 = sqlite3VdbeCurrentAddr(v); | |
| 3333 | |
| 3334 /* Check if the index cursor is past the end of the range. */ | |
| 3335 if( nConstraint ){ | |
| 3336 op = aEndOp[bRev*2 + endEq]; | |
| 3337 sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint); | |
| 3338 testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT ); | |
| 3339 testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE ); | |
| 3340 testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT ); | |
| 3341 testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE ); | |
| 3342 } | |
| 3343 | |
| 3344 /* Seek the table cursor, if required */ | |
| 3345 disableTerm(pLevel, pRangeStart); | |
| 3346 disableTerm(pLevel, pRangeEnd); | |
| 3347 if( omitTable ){ | |
| 3348 /* pIdx is a covering index. No need to access the main table. */ | |
| 3349 }else if( HasRowid(pIdx->pTable) ){ | |
| 3350 iRowidReg = ++pParse->nMem; | |
| 3351 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg); | |
| 3352 sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg); | |
| 3353 sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */ | |
| 3354 }else if( iCur!=iIdxCur ){ | |
| 3355 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable); | |
| 3356 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol); | |
| 3357 for(j=0; j<pPk->nKeyCol; j++){ | |
| 3358 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]); | |
| 3359 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j); | |
| 3360 } | |
| 3361 sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont, | |
| 3362 iRowidReg, pPk->nKeyCol); VdbeCoverage(v); | |
| 3363 } | |
| 3364 | |
| 3365 /* Record the instruction used to terminate the loop. Disable | |
| 3366 ** WHERE clause terms made redundant by the index range scan. | |
| 3367 */ | |
| 3368 if( pLoop->wsFlags & WHERE_ONEROW ){ | |
| 3369 pLevel->op = OP_Noop; | |
| 3370 }else if( bRev ){ | |
| 3371 pLevel->op = OP_Prev; | |
| 3372 }else{ | |
| 3373 pLevel->op = OP_Next; | |
| 3374 } | |
| 3375 pLevel->p1 = iIdxCur; | |
| 3376 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0; | |
| 3377 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){ | |
| 3378 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; | |
| 3379 }else{ | |
| 3380 assert( pLevel->p5==0 ); | |
| 3381 } | |
| 3382 }else | |
| 3383 | |
| 3384 #ifndef SQLITE_OMIT_OR_OPTIMIZATION | |
| 3385 if( pLoop->wsFlags & WHERE_MULTI_OR ){ | |
| 3386 /* Case 5: Two or more separately indexed terms connected by OR | |
| 3387 ** | |
| 3388 ** Example: | |
| 3389 ** | |
| 3390 ** CREATE TABLE t1(a,b,c,d); | |
| 3391 ** CREATE INDEX i1 ON t1(a); | |
| 3392 ** CREATE INDEX i2 ON t1(b); | |
| 3393 ** CREATE INDEX i3 ON t1(c); | |
| 3394 ** | |
| 3395 ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13) | |
| 3396 ** | |
| 3397 ** In the example, there are three indexed terms connected by OR. | |
| 3398 ** The top of the loop looks like this: | |
| 3399 ** | |
| 3400 ** Null 1 # Zero the rowset in reg 1 | |
| 3401 ** | |
| 3402 ** Then, for each indexed term, the following. The arguments to | |
| 3403 ** RowSetTest are such that the rowid of the current row is inserted | |
| 3404 ** into the RowSet. If it is already present, control skips the | |
| 3405 ** Gosub opcode and jumps straight to the code generated by WhereEnd(). | |
| 3406 ** | |
| 3407 ** sqlite3WhereBegin(<term>) | |
| 3408 ** RowSetTest # Insert rowid into rowset | |
| 3409 ** Gosub 2 A | |
| 3410 ** sqlite3WhereEnd() | |
| 3411 ** | |
| 3412 ** Following the above, code to terminate the loop. Label A, the target | |
| 3413 ** of the Gosub above, jumps to the instruction right after the Goto. | |
| 3414 ** | |
| 3415 ** Null 1 # Zero the rowset in reg 1 | |
| 3416 ** Goto B # The loop is finished. | |
| 3417 ** | |
| 3418 ** A: <loop body> # Return data, whatever. | |
| 3419 ** | |
| 3420 ** Return 2 # Jump back to the Gosub | |
| 3421 ** | |
| 3422 ** B: <after the loop> | |
| 3423 ** | |
| 3424 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then | |
| 3425 ** use an ephemeral index instead of a RowSet to record the primary | |
| 3426 ** keys of the rows we have already seen. | |
| 3427 ** | |
| 3428 */ | |
| 3429 WhereClause *pOrWc; /* The OR-clause broken out into subterms */ | |
| 3430 SrcList *pOrTab; /* Shortened table list or OR-clause generation */ | |
| 3431 Index *pCov = 0; /* Potential covering index (or NULL) */ | |
| 3432 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */ | |
| 3433 | |
| 3434 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */ | |
| 3435 int regRowset = 0; /* Register for RowSet object */ | |
| 3436 int regRowid = 0; /* Register holding rowid */ | |
| 3437 int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */ | |
| 3438 int iRetInit; /* Address of regReturn init */ | |
| 3439 int untestedTerms = 0; /* Some terms not completely tested */ | |
| 3440 int ii; /* Loop counter */ | |
| 3441 u16 wctrlFlags; /* Flags for sub-WHERE clause */ | |
| 3442 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */ | |
| 3443 Table *pTab = pTabItem->pTab; | |
| 3444 | |
| 3445 pTerm = pLoop->aLTerm[0]; | |
| 3446 assert( pTerm!=0 ); | |
| 3447 assert( pTerm->eOperator & WO_OR ); | |
| 3448 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 ); | |
| 3449 pOrWc = &pTerm->u.pOrInfo->wc; | |
| 3450 pLevel->op = OP_Return; | |
| 3451 pLevel->p1 = regReturn; | |
| 3452 | |
| 3453 /* Set up a new SrcList in pOrTab containing the table being scanned | |
| 3454 ** by this loop in the a[0] slot and all notReady tables in a[1..] slots. | |
| 3455 ** This becomes the SrcList in the recursive call to sqlite3WhereBegin(). | |
| 3456 */ | |
| 3457 if( pWInfo->nLevel>1 ){ | |
| 3458 int nNotReady; /* The number of notReady tables */ | |
| 3459 struct SrcList_item *origSrc; /* Original list of tables */ | |
| 3460 nNotReady = pWInfo->nLevel - iLevel - 1; | |
| 3461 pOrTab = sqlite3StackAllocRaw(db, | |
| 3462 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0])); | |
| 3463 if( pOrTab==0 ) return notReady; | |
| 3464 pOrTab->nAlloc = (u8)(nNotReady + 1); | |
| 3465 pOrTab->nSrc = pOrTab->nAlloc; | |
| 3466 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem)); | |
| 3467 origSrc = pWInfo->pTabList->a; | |
| 3468 for(k=1; k<=nNotReady; k++){ | |
| 3469 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k])); | |
| 3470 } | |
| 3471 }else{ | |
| 3472 pOrTab = pWInfo->pTabList; | |
| 3473 } | |
| 3474 | |
| 3475 /* Initialize the rowset register to contain NULL. An SQL NULL is | |
| 3476 ** equivalent to an empty rowset. Or, create an ephemeral index | |
| 3477 ** capable of holding primary keys in the case of a WITHOUT ROWID. | |
| 3478 ** | |
| 3479 ** Also initialize regReturn to contain the address of the instruction | |
| 3480 ** immediately following the OP_Return at the bottom of the loop. This | |
| 3481 ** is required in a few obscure LEFT JOIN cases where control jumps | |
| 3482 ** over the top of the loop into the body of it. In this case the | |
| 3483 ** correct response for the end-of-loop code (the OP_Return) is to | |
| 3484 ** fall through to the next instruction, just as an OP_Next does if | |
| 3485 ** called on an uninitialized cursor. | |
| 3486 */ | |
| 3487 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ | |
| 3488 if( HasRowid(pTab) ){ | |
| 3489 regRowset = ++pParse->nMem; | |
| 3490 sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset); | |
| 3491 }else{ | |
| 3492 Index *pPk = sqlite3PrimaryKeyIndex(pTab); | |
| 3493 regRowset = pParse->nTab++; | |
| 3494 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol); | |
| 3495 sqlite3VdbeSetP4KeyInfo(pParse, pPk); | |
| 3496 } | |
| 3497 regRowid = ++pParse->nMem; | |
| 3498 } | |
| 3499 iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn); | |
| 3500 | |
| 3501 /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y | |
| 3502 ** Then for every term xN, evaluate as the subexpression: xN AND z | |
| 3503 ** That way, terms in y that are factored into the disjunction will | |
| 3504 ** be picked up by the recursive calls to sqlite3WhereBegin() below. | |
| 3505 ** | |
| 3506 ** Actually, each subexpression is converted to "xN AND w" where w is | |
| 3507 ** the "interesting" terms of z - terms that did not originate in the | |
| 3508 ** ON or USING clause of a LEFT JOIN, and terms that are usable as | |
| 3509 ** indices. | |
| 3510 ** | |
| 3511 ** This optimization also only applies if the (x1 OR x2 OR ...) term | |
| 3512 ** is not contained in the ON clause of a LEFT JOIN. | |
| 3513 ** See ticket http://www.sqlite.org/src/info/f2369304e4 | |
| 3514 */ | |
| 3515 if( pWC->nTerm>1 ){ | |
| 3516 int iTerm; | |
| 3517 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){ | |
| 3518 Expr *pExpr = pWC->a[iTerm].pExpr; | |
| 3519 if( &pWC->a[iTerm] == pTerm ) continue; | |
| 3520 if( ExprHasProperty(pExpr, EP_FromJoin) ) continue; | |
| 3521 testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO ); | |
| 3522 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL ); | |
| 3523 if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue; | |
| 3524 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue; | |
| 3525 pExpr = sqlite3ExprDup(db, pExpr, 0); | |
| 3526 pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr); | |
| 3527 } | |
| 3528 if( pAndExpr ){ | |
| 3529 pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0); | |
| 3530 } | |
| 3531 } | |
| 3532 | |
| 3533 /* Run a separate WHERE clause for each term of the OR clause. After | |
| 3534 ** eliminating duplicates from other WHERE clauses, the action for each | |
| 3535 ** sub-WHERE clause is to to invoke the main loop body as a subroutine. | |
| 3536 */ | |
| 3537 wctrlFlags = WHERE_OMIT_OPEN_CLOSE | |
| 3538 | WHERE_FORCE_TABLE | |
| 3539 | WHERE_ONETABLE_ONLY; | |
| 3540 for(ii=0; ii<pOrWc->nTerm; ii++){ | |
| 3541 WhereTerm *pOrTerm = &pOrWc->a[ii]; | |
| 3542 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){ | |
| 3543 WhereInfo *pSubWInfo; /* Info for single OR-term scan */ | |
| 3544 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */ | |
| 3545 int j1 = 0; /* Address of jump operation */ | |
| 3546 if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){ | |
| 3547 pAndExpr->pLeft = pOrExpr; | |
| 3548 pOrExpr = pAndExpr; | |
| 3549 } | |
| 3550 /* Loop through table entries that match term pOrTerm. */ | |
| 3551 WHERETRACE(0xffff, ("Subplan for OR-clause:\n")); | |
| 3552 pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0, | |
| 3553 wctrlFlags, iCovCur); | |
| 3554 assert( pSubWInfo || pParse->nErr || db->mallocFailed ); | |
| 3555 if( pSubWInfo ){ | |
| 3556 WhereLoop *pSubLoop; | |
| 3557 explainOneScan( | |
| 3558 pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0 | |
| 3559 ); | |
| 3560 /* This is the sub-WHERE clause body. First skip over | |
| 3561 ** duplicate rows from prior sub-WHERE clauses, and record the | |
| 3562 ** rowid (or PRIMARY KEY) for the current row so that the same | |
| 3563 ** row will be skipped in subsequent sub-WHERE clauses. | |
| 3564 */ | |
| 3565 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){ | |
| 3566 int r; | |
| 3567 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii); | |
| 3568 if( HasRowid(pTab) ){ | |
| 3569 r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0); | |
| 3570 j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet); | |
| 3571 VdbeCoverage(v); | |
| 3572 }else{ | |
| 3573 Index *pPk = sqlite3PrimaryKeyIndex(pTab); | |
| 3574 int nPk = pPk->nKeyCol; | |
| 3575 int iPk; | |
| 3576 | |
| 3577 /* Read the PK into an array of temp registers. */ | |
| 3578 r = sqlite3GetTempRange(pParse, nPk); | |
| 3579 for(iPk=0; iPk<nPk; iPk++){ | |
| 3580 int iCol = pPk->aiColumn[iPk]; | |
| 3581 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0); | |
| 3582 } | |
| 3583 | |
| 3584 /* Check if the temp table already contains this key. If so, | |
| 3585 ** the row has already been included in the result set and | |
| 3586 ** can be ignored (by jumping past the Gosub below). Otherwise, | |
| 3587 ** insert the key into the temp table and proceed with processing | |
| 3588 ** the row. | |
| 3589 ** | |
| 3590 ** Use some of the same optimizations as OP_RowSetTest: If iSet | |
| 3591 ** is zero, assume that the key cannot already be present in | |
| 3592 ** the temp table. And if iSet is -1, assume that there is no | |
| 3593 ** need to insert the key into the temp table, as it will never | |
| 3594 ** be tested for. */ | |
| 3595 if( iSet ){ | |
| 3596 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk); | |
| 3597 VdbeCoverage(v); | |
| 3598 } | |
| 3599 if( iSet>=0 ){ | |
| 3600 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid); | |
| 3601 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0); | |
| 3602 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT); | |
| 3603 } | |
| 3604 | |
| 3605 /* Release the array of temp registers */ | |
| 3606 sqlite3ReleaseTempRange(pParse, r, nPk); | |
| 3607 } | |
| 3608 } | |
| 3609 | |
| 3610 /* Invoke the main loop body as a subroutine */ | |
| 3611 sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody); | |
| 3612 | |
| 3613 /* Jump here (skipping the main loop body subroutine) if the | |
| 3614 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */ | |
| 3615 if( j1 ) sqlite3VdbeJumpHere(v, j1); | |
| 3616 | |
| 3617 /* The pSubWInfo->untestedTerms flag means that this OR term | |
| 3618 ** contained one or more AND term from a notReady table. The | |
| 3619 ** terms from the notReady table could not be tested and will | |
| 3620 ** need to be tested later. | |
| 3621 */ | |
| 3622 if( pSubWInfo->untestedTerms ) untestedTerms = 1; | |
| 3623 | |
| 3624 /* If all of the OR-connected terms are optimized using the same | |
| 3625 ** index, and the index is opened using the same cursor number | |
| 3626 ** by each call to sqlite3WhereBegin() made by this loop, it may | |
| 3627 ** be possible to use that index as a covering index. | |
| 3628 ** | |
| 3629 ** If the call to sqlite3WhereBegin() above resulted in a scan that | |
| 3630 ** uses an index, and this is either the first OR-connected term | |
| 3631 ** processed or the index is the same as that used by all previous | |
| 3632 ** terms, set pCov to the candidate covering index. Otherwise, set | |
| 3633 ** pCov to NULL to indicate that no candidate covering index will | |
| 3634 ** be available. | |
| 3635 */ | |
| 3636 pSubLoop = pSubWInfo->a[0].pWLoop; | |
| 3637 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); | |
| 3638 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0 | |
| 3639 && (ii==0 || pSubLoop->u.btree.pIndex==pCov) | |
| 3640 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex)) | |
| 3641 ){ | |
| 3642 assert( pSubWInfo->a[0].iIdxCur==iCovCur ); | |
| 3643 pCov = pSubLoop->u.btree.pIndex; | |
| 3644 wctrlFlags |= WHERE_REOPEN_IDX; | |
| 3645 }else{ | |
| 3646 pCov = 0; | |
| 3647 } | |
| 3648 | |
| 3649 /* Finish the loop through table entries that match term pOrTerm. */ | |
| 3650 sqlite3WhereEnd(pSubWInfo); | |
| 3651 } | |
| 3652 } | |
| 3653 } | |
| 3654 pLevel->u.pCovidx = pCov; | |
| 3655 if( pCov ) pLevel->iIdxCur = iCovCur; | |
| 3656 if( pAndExpr ){ | |
| 3657 pAndExpr->pLeft = 0; | |
| 3658 sqlite3ExprDelete(db, pAndExpr); | |
| 3659 } | |
| 3660 sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v)); | |
| 3661 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk); | |
| 3662 sqlite3VdbeResolveLabel(v, iLoopBody); | |
| 3663 | |
| 3664 if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab); | |
| 3665 if( !untestedTerms ) disableTerm(pLevel, pTerm); | |
| 3666 }else | |
| 3667 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */ | |
| 3668 | |
| 3669 { | |
| 3670 /* Case 6: There is no usable index. We must do a complete | |
| 3671 ** scan of the entire table. | |
| 3672 */ | |
| 3673 static const u8 aStep[] = { OP_Next, OP_Prev }; | |
| 3674 static const u8 aStart[] = { OP_Rewind, OP_Last }; | |
| 3675 assert( bRev==0 || bRev==1 ); | |
| 3676 if( pTabItem->isRecursive ){ | |
| 3677 /* Tables marked isRecursive have only a single row that is stored in | |
| 3678 ** a pseudo-cursor. No need to Rewind or Next such cursors. */ | |
| 3679 pLevel->op = OP_Noop; | |
| 3680 }else{ | |
| 3681 pLevel->op = aStep[bRev]; | |
| 3682 pLevel->p1 = iCur; | |
| 3683 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk); | |
| 3684 VdbeCoverageIf(v, bRev==0); | |
| 3685 VdbeCoverageIf(v, bRev!=0); | |
| 3686 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP; | |
| 3687 } | |
| 3688 } | |
| 3689 | |
| 3690 /* Insert code to test every subexpression that can be completely | |
| 3691 ** computed using the current set of tables. | |
| 3692 */ | |
| 3693 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ | |
| 3694 Expr *pE; | |
| 3695 testcase( pTerm->wtFlags & TERM_VIRTUAL ); | |
| 3696 testcase( pTerm->wtFlags & TERM_CODED ); | |
| 3697 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; | |
| 3698 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ | |
| 3699 testcase( pWInfo->untestedTerms==0 | |
| 3700 && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ); | |
| 3701 pWInfo->untestedTerms = 1; | |
| 3702 continue; | |
| 3703 } | |
| 3704 pE = pTerm->pExpr; | |
| 3705 assert( pE!=0 ); | |
| 3706 if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ | |
| 3707 continue; | |
| 3708 } | |
| 3709 sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL); | |
| 3710 pTerm->wtFlags |= TERM_CODED; | |
| 3711 } | |
| 3712 | |
| 3713 /* Insert code to test for implied constraints based on transitivity | |
| 3714 ** of the "==" operator. | |
| 3715 ** | |
| 3716 ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123" | |
| 3717 ** and we are coding the t1 loop and the t2 loop has not yet coded, | |
| 3718 ** then we cannot use the "t1.a=t2.b" constraint, but we can code | |
| 3719 ** the implied "t1.a=123" constraint. | |
| 3720 */ | |
| 3721 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){ | |
| 3722 Expr *pE, *pEAlt; | |
| 3723 WhereTerm *pAlt; | |
| 3724 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; | |
| 3725 if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue; | |
| 3726 if( pTerm->leftCursor!=iCur ) continue; | |
| 3727 if( pLevel->iLeftJoin ) continue; | |
| 3728 pE = pTerm->pExpr; | |
| 3729 assert( !ExprHasProperty(pE, EP_FromJoin) ); | |
| 3730 assert( (pTerm->prereqRight & pLevel->notReady)!=0 ); | |
| 3731 pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0); | |
| 3732 if( pAlt==0 ) continue; | |
| 3733 if( pAlt->wtFlags & (TERM_CODED) ) continue; | |
| 3734 testcase( pAlt->eOperator & WO_EQ ); | |
| 3735 testcase( pAlt->eOperator & WO_IN ); | |
| 3736 VdbeModuleComment((v, "begin transitive constraint")); | |
| 3737 pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt)); | |
| 3738 if( pEAlt ){ | |
| 3739 *pEAlt = *pAlt->pExpr; | |
| 3740 pEAlt->pLeft = pE->pLeft; | |
| 3741 sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL); | |
| 3742 sqlite3StackFree(db, pEAlt); | |
| 3743 } | |
| 3744 } | |
| 3745 | |
| 3746 /* For a LEFT OUTER JOIN, generate code that will record the fact that | |
| 3747 ** at least one row of the right table has matched the left table. | |
| 3748 */ | |
| 3749 if( pLevel->iLeftJoin ){ | |
| 3750 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v); | |
| 3751 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); | |
| 3752 VdbeComment((v, "record LEFT JOIN hit")); | |
| 3753 sqlite3ExprCacheClear(pParse); | |
| 3754 for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){ | |
| 3755 testcase( pTerm->wtFlags & TERM_VIRTUAL ); | |
| 3756 testcase( pTerm->wtFlags & TERM_CODED ); | |
| 3757 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue; | |
| 3758 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){ | |
| 3759 assert( pWInfo->untestedTerms ); | |
| 3760 continue; | |
| 3761 } | |
| 3762 assert( pTerm->pExpr ); | |
| 3763 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL); | |
| 3764 pTerm->wtFlags |= TERM_CODED; | |
| 3765 } | |
| 3766 } | |
| 3767 | |
| 3768 return pLevel->notReady; | |
| 3769 } | |
| 3770 | 1620 |
| 3771 #ifdef WHERETRACE_ENABLED | 1621 #ifdef WHERETRACE_ENABLED |
| 3772 /* | 1622 /* |
| 3773 ** Print the content of a WhereTerm object | 1623 ** Print the content of a WhereTerm object |
| 3774 */ | 1624 */ |
| 3775 static void whereTermPrint(WhereTerm *pTerm, int iTerm){ | 1625 static void whereTermPrint(WhereTerm *pTerm, int iTerm){ |
| 3776 if( pTerm==0 ){ | 1626 if( pTerm==0 ){ |
| 3777 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); | 1627 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm); |
| 3778 }else{ | 1628 }else{ |
| 3779 char zType[4]; | 1629 char zType[4]; |
| 3780 memcpy(zType, "...", 4); | 1630 memcpy(zType, "...", 4); |
| 3781 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; | 1631 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V'; |
| 3782 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; | 1632 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E'; |
| 3783 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; | 1633 if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L'; |
| 3784 sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n", | 1634 sqlite3DebugPrintf( |
| 3785 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb, | 1635 "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n", |
| 3786 pTerm->eOperator); | 1636 iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb, |
| 1637 pTerm->eOperator, pTerm->wtFlags); |
| 3787 sqlite3TreeViewExpr(0, pTerm->pExpr, 0); | 1638 sqlite3TreeViewExpr(0, pTerm->pExpr, 0); |
| 3788 } | 1639 } |
| 3789 } | 1640 } |
| 3790 #endif | 1641 #endif |
| 3791 | 1642 |
| 3792 #ifdef WHERETRACE_ENABLED | 1643 #ifdef WHERETRACE_ENABLED |
| 3793 /* | 1644 /* |
| 3794 ** Print a WhereLoop object for debugging purposes | 1645 ** Print a WhereLoop object for debugging purposes |
| 3795 */ | 1646 */ |
| 3796 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){ | 1647 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){ |
| (...skipping 22 matching lines...) Expand all Loading... |
| 3819 if( p->u.vtab.idxStr ){ | 1670 if( p->u.vtab.idxStr ){ |
| 3820 z = sqlite3_mprintf("(%d,\"%s\",%x)", | 1671 z = sqlite3_mprintf("(%d,\"%s\",%x)", |
| 3821 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); | 1672 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask); |
| 3822 }else{ | 1673 }else{ |
| 3823 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); | 1674 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask); |
| 3824 } | 1675 } |
| 3825 sqlite3DebugPrintf(" %-19s", z); | 1676 sqlite3DebugPrintf(" %-19s", z); |
| 3826 sqlite3_free(z); | 1677 sqlite3_free(z); |
| 3827 } | 1678 } |
| 3828 if( p->wsFlags & WHERE_SKIPSCAN ){ | 1679 if( p->wsFlags & WHERE_SKIPSCAN ){ |
| 3829 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->u.btree.nSkip); | 1680 sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip); |
| 3830 }else{ | 1681 }else{ |
| 3831 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); | 1682 sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm); |
| 3832 } | 1683 } |
| 3833 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); | 1684 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut); |
| 3834 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ | 1685 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){ |
| 3835 int i; | 1686 int i; |
| 3836 for(i=0; i<p->nLTerm; i++){ | 1687 for(i=0; i<p->nLTerm; i++){ |
| 3837 whereTermPrint(p->aLTerm[i], i); | 1688 whereTermPrint(p->aLTerm[i], i); |
| 3838 } | 1689 } |
| 3839 } | 1690 } |
| (...skipping 15 matching lines...) Expand all Loading... |
| 3855 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. | 1706 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact. |
| 3856 */ | 1707 */ |
| 3857 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ | 1708 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){ |
| 3858 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ | 1709 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){ |
| 3859 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ | 1710 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){ |
| 3860 sqlite3_free(p->u.vtab.idxStr); | 1711 sqlite3_free(p->u.vtab.idxStr); |
| 3861 p->u.vtab.needFree = 0; | 1712 p->u.vtab.needFree = 0; |
| 3862 p->u.vtab.idxStr = 0; | 1713 p->u.vtab.idxStr = 0; |
| 3863 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ | 1714 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){ |
| 3864 sqlite3DbFree(db, p->u.btree.pIndex->zColAff); | 1715 sqlite3DbFree(db, p->u.btree.pIndex->zColAff); |
| 3865 sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo); | |
| 3866 sqlite3DbFree(db, p->u.btree.pIndex); | 1716 sqlite3DbFree(db, p->u.btree.pIndex); |
| 3867 p->u.btree.pIndex = 0; | 1717 p->u.btree.pIndex = 0; |
| 3868 } | 1718 } |
| 3869 } | 1719 } |
| 3870 } | 1720 } |
| 3871 | 1721 |
| 3872 /* | 1722 /* |
| 3873 ** Deallocate internal memory used by a WhereLoop object | 1723 ** Deallocate internal memory used by a WhereLoop object |
| 3874 */ | 1724 */ |
| 3875 static void whereLoopClear(sqlite3 *db, WhereLoop *p){ | 1725 static void whereLoopClear(sqlite3 *db, WhereLoop *p){ |
| (...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 3919 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ | 1769 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){ |
| 3920 whereLoopClear(db, p); | 1770 whereLoopClear(db, p); |
| 3921 sqlite3DbFree(db, p); | 1771 sqlite3DbFree(db, p); |
| 3922 } | 1772 } |
| 3923 | 1773 |
| 3924 /* | 1774 /* |
| 3925 ** Free a WhereInfo structure | 1775 ** Free a WhereInfo structure |
| 3926 */ | 1776 */ |
| 3927 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ | 1777 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){ |
| 3928 if( ALWAYS(pWInfo) ){ | 1778 if( ALWAYS(pWInfo) ){ |
| 3929 whereClauseClear(&pWInfo->sWC); | 1779 int i; |
| 1780 for(i=0; i<pWInfo->nLevel; i++){ |
| 1781 WhereLevel *pLevel = &pWInfo->a[i]; |
| 1782 if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){ |
| 1783 sqlite3DbFree(db, pLevel->u.in.aInLoop); |
| 1784 } |
| 1785 } |
| 1786 sqlite3WhereClauseClear(&pWInfo->sWC); |
| 3930 while( pWInfo->pLoops ){ | 1787 while( pWInfo->pLoops ){ |
| 3931 WhereLoop *p = pWInfo->pLoops; | 1788 WhereLoop *p = pWInfo->pLoops; |
| 3932 pWInfo->pLoops = p->pNextLoop; | 1789 pWInfo->pLoops = p->pNextLoop; |
| 3933 whereLoopDelete(db, p); | 1790 whereLoopDelete(db, p); |
| 3934 } | 1791 } |
| 3935 sqlite3DbFree(db, pWInfo); | 1792 sqlite3DbFree(db, pWInfo); |
| 3936 } | 1793 } |
| 3937 } | 1794 } |
| 3938 | 1795 |
| 3939 /* | 1796 /* |
| 3940 ** Return TRUE if both of the following are true: | 1797 ** Return TRUE if all of the following are true: |
| 3941 ** | 1798 ** |
| 3942 ** (1) X has the same or lower cost that Y | 1799 ** (1) X has the same or lower cost that Y |
| 3943 ** (2) X is a proper subset of Y | 1800 ** (2) X is a proper subset of Y |
| 1801 ** (3) X skips at least as many columns as Y |
| 3944 ** | 1802 ** |
| 3945 ** By "proper subset" we mean that X uses fewer WHERE clause terms | 1803 ** By "proper subset" we mean that X uses fewer WHERE clause terms |
| 3946 ** than Y and that every WHERE clause term used by X is also used | 1804 ** than Y and that every WHERE clause term used by X is also used |
| 3947 ** by Y. | 1805 ** by Y. |
| 3948 ** | 1806 ** |
| 3949 ** If X is a proper subset of Y then Y is a better choice and ought | 1807 ** If X is a proper subset of Y then Y is a better choice and ought |
| 3950 ** to have a lower cost. This routine returns TRUE when that cost | 1808 ** to have a lower cost. This routine returns TRUE when that cost |
| 3951 ** relationship is inverted and needs to be adjusted. | 1809 ** relationship is inverted and needs to be adjusted. The third rule |
| 1810 ** was added because if X uses skip-scan less than Y it still might |
| 1811 ** deserve a lower cost even if it is a proper subset of Y. |
| 3952 */ | 1812 */ |
| 3953 static int whereLoopCheaperProperSubset( | 1813 static int whereLoopCheaperProperSubset( |
| 3954 const WhereLoop *pX, /* First WhereLoop to compare */ | 1814 const WhereLoop *pX, /* First WhereLoop to compare */ |
| 3955 const WhereLoop *pY /* Compare against this WhereLoop */ | 1815 const WhereLoop *pY /* Compare against this WhereLoop */ |
| 3956 ){ | 1816 ){ |
| 3957 int i, j; | 1817 int i, j; |
| 3958 if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */ | 1818 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){ |
| 1819 return 0; /* X is not a subset of Y */ |
| 1820 } |
| 1821 if( pY->nSkip > pX->nSkip ) return 0; |
| 3959 if( pX->rRun >= pY->rRun ){ | 1822 if( pX->rRun >= pY->rRun ){ |
| 3960 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */ | 1823 if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */ |
| 3961 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */ | 1824 if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */ |
| 3962 } | 1825 } |
| 3963 for(i=pX->nLTerm-1; i>=0; i--){ | 1826 for(i=pX->nLTerm-1; i>=0; i--){ |
| 1827 if( pX->aLTerm[i]==0 ) continue; |
| 3964 for(j=pY->nLTerm-1; j>=0; j--){ | 1828 for(j=pY->nLTerm-1; j>=0; j--){ |
| 3965 if( pY->aLTerm[j]==pX->aLTerm[i] ) break; | 1829 if( pY->aLTerm[j]==pX->aLTerm[i] ) break; |
| 3966 } | 1830 } |
| 3967 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ | 1831 if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */ |
| 3968 } | 1832 } |
| 3969 return 1; /* All conditions meet */ | 1833 return 1; /* All conditions meet */ |
| 3970 } | 1834 } |
| 3971 | 1835 |
| 3972 /* | 1836 /* |
| 3973 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so | 1837 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so |
| 3974 ** that: | 1838 ** that: |
| 3975 ** | 1839 ** |
| 3976 ** (1) pTemplate costs less than any other WhereLoops that are a proper | 1840 ** (1) pTemplate costs less than any other WhereLoops that are a proper |
| 3977 ** subset of pTemplate | 1841 ** subset of pTemplate |
| 3978 ** | 1842 ** |
| 3979 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate | 1843 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate |
| 3980 ** is a proper subset. | 1844 ** is a proper subset. |
| 3981 ** | 1845 ** |
| 3982 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer | 1846 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer |
| 3983 ** WHERE clause terms than Y and that every WHERE clause term used by X is | 1847 ** WHERE clause terms than Y and that every WHERE clause term used by X is |
| 3984 ** also used by Y. | 1848 ** also used by Y. |
| 3985 ** | |
| 3986 ** This adjustment is omitted for SKIPSCAN loops. In a SKIPSCAN loop, the | |
| 3987 ** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE | |
| 3988 ** clause terms covered, since some of the first nLTerm entries in aLTerm[] | |
| 3989 ** will be NULL (because they are skipped). That makes it more difficult | |
| 3990 ** to compare the loops. We could add extra code to do the comparison, and | |
| 3991 ** perhaps we will someday. But SKIPSCAN is sufficiently uncommon, and this | |
| 3992 ** adjustment is sufficient minor, that it is very difficult to construct | |
| 3993 ** a test case where the extra code would improve the query plan. Better | |
| 3994 ** to avoid the added complexity and just omit cost adjustments to SKIPSCAN | |
| 3995 ** loops. | |
| 3996 */ | 1849 */ |
| 3997 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ | 1850 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){ |
| 3998 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; | 1851 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return; |
| 3999 if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return; | |
| 4000 for(; p; p=p->pNextLoop){ | 1852 for(; p; p=p->pNextLoop){ |
| 4001 if( p->iTab!=pTemplate->iTab ) continue; | 1853 if( p->iTab!=pTemplate->iTab ) continue; |
| 4002 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; | 1854 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue; |
| 4003 if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue; | |
| 4004 if( whereLoopCheaperProperSubset(p, pTemplate) ){ | 1855 if( whereLoopCheaperProperSubset(p, pTemplate) ){ |
| 4005 /* Adjust pTemplate cost downward so that it is cheaper than its | 1856 /* Adjust pTemplate cost downward so that it is cheaper than its |
| 4006 ** subset p */ | 1857 ** subset p. */ |
| 1858 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", |
| 1859 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1)); |
| 4007 pTemplate->rRun = p->rRun; | 1860 pTemplate->rRun = p->rRun; |
| 4008 pTemplate->nOut = p->nOut - 1; | 1861 pTemplate->nOut = p->nOut - 1; |
| 4009 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){ | 1862 }else if( whereLoopCheaperProperSubset(pTemplate, p) ){ |
| 4010 /* Adjust pTemplate cost upward so that it is costlier than p since | 1863 /* Adjust pTemplate cost upward so that it is costlier than p since |
| 4011 ** pTemplate is a proper subset of p */ | 1864 ** pTemplate is a proper subset of p */ |
| 1865 WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n", |
| 1866 pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1)); |
| 4012 pTemplate->rRun = p->rRun; | 1867 pTemplate->rRun = p->rRun; |
| 4013 pTemplate->nOut = p->nOut + 1; | 1868 pTemplate->nOut = p->nOut + 1; |
| 4014 } | 1869 } |
| 4015 } | 1870 } |
| 4016 } | 1871 } |
| 4017 | 1872 |
| 4018 /* | 1873 /* |
| 4019 ** Search the list of WhereLoops in *ppPrev looking for one that can be | 1874 ** Search the list of WhereLoops in *ppPrev looking for one that can be |
| 4020 ** supplanted by pTemplate. | 1875 ** supplanted by pTemplate. |
| 4021 ** | 1876 ** |
| (...skipping 24 matching lines...) Expand all Loading... |
| 4046 assert( p->rSetup==0 || pTemplate->rSetup==0 | 1901 assert( p->rSetup==0 || pTemplate->rSetup==0 |
| 4047 || p->rSetup==pTemplate->rSetup ); | 1902 || p->rSetup==pTemplate->rSetup ); |
| 4048 | 1903 |
| 4049 /* whereLoopAddBtree() always generates and inserts the automatic index | 1904 /* whereLoopAddBtree() always generates and inserts the automatic index |
| 4050 ** case first. Hence compatible candidate WhereLoops never have a larger | 1905 ** case first. Hence compatible candidate WhereLoops never have a larger |
| 4051 ** rSetup. Call this SETUP-INVARIANT */ | 1906 ** rSetup. Call this SETUP-INVARIANT */ |
| 4052 assert( p->rSetup>=pTemplate->rSetup ); | 1907 assert( p->rSetup>=pTemplate->rSetup ); |
| 4053 | 1908 |
| 4054 /* Any loop using an appliation-defined index (or PRIMARY KEY or | 1909 /* Any loop using an appliation-defined index (or PRIMARY KEY or |
| 4055 ** UNIQUE constraint) with one or more == constraints is better | 1910 ** UNIQUE constraint) with one or more == constraints is better |
| 4056 ** than an automatic index. */ | 1911 ** than an automatic index. Unless it is a skip-scan. */ |
| 4057 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 | 1912 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 |
| 1913 && (pTemplate->nSkip)==0 |
| 4058 && (pTemplate->wsFlags & WHERE_INDEXED)!=0 | 1914 && (pTemplate->wsFlags & WHERE_INDEXED)!=0 |
| 4059 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0 | 1915 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0 |
| 4060 && (p->prereq & pTemplate->prereq)==pTemplate->prereq | 1916 && (p->prereq & pTemplate->prereq)==pTemplate->prereq |
| 4061 ){ | 1917 ){ |
| 4062 break; | 1918 break; |
| 4063 } | 1919 } |
| 4064 | 1920 |
| 4065 /* If existing WhereLoop p is better than pTemplate, pTemplate can be | 1921 /* If existing WhereLoop p is better than pTemplate, pTemplate can be |
| 4066 ** discarded. WhereLoop p is better if: | 1922 ** discarded. WhereLoop p is better if: |
| 4067 ** (1) p has no more dependencies than pTemplate, and | 1923 ** (1) p has no more dependencies than pTemplate, and |
| (...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 4117 */ | 1973 */ |
| 4118 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ | 1974 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){ |
| 4119 WhereLoop **ppPrev, *p; | 1975 WhereLoop **ppPrev, *p; |
| 4120 WhereInfo *pWInfo = pBuilder->pWInfo; | 1976 WhereInfo *pWInfo = pBuilder->pWInfo; |
| 4121 sqlite3 *db = pWInfo->pParse->db; | 1977 sqlite3 *db = pWInfo->pParse->db; |
| 4122 | 1978 |
| 4123 /* If pBuilder->pOrSet is defined, then only keep track of the costs | 1979 /* If pBuilder->pOrSet is defined, then only keep track of the costs |
| 4124 ** and prereqs. | 1980 ** and prereqs. |
| 4125 */ | 1981 */ |
| 4126 if( pBuilder->pOrSet!=0 ){ | 1982 if( pBuilder->pOrSet!=0 ){ |
| 1983 if( pTemplate->nLTerm ){ |
| 4127 #if WHERETRACE_ENABLED | 1984 #if WHERETRACE_ENABLED |
| 4128 u16 n = pBuilder->pOrSet->n; | 1985 u16 n = pBuilder->pOrSet->n; |
| 4129 int x = | 1986 int x = |
| 4130 #endif | 1987 #endif |
| 4131 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, | 1988 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun, |
| 4132 pTemplate->nOut); | 1989 pTemplate->nOut); |
| 4133 #if WHERETRACE_ENABLED /* 0x8 */ | 1990 #if WHERETRACE_ENABLED /* 0x8 */ |
| 4134 if( sqlite3WhereTrace & 0x8 ){ | 1991 if( sqlite3WhereTrace & 0x8 ){ |
| 4135 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); | 1992 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n); |
| 4136 whereLoopPrint(pTemplate, pBuilder->pWC); | 1993 whereLoopPrint(pTemplate, pBuilder->pWC); |
| 1994 } |
| 1995 #endif |
| 4137 } | 1996 } |
| 4138 #endif | |
| 4139 return SQLITE_OK; | 1997 return SQLITE_OK; |
| 4140 } | 1998 } |
| 4141 | 1999 |
| 4142 /* Look for an existing WhereLoop to replace with pTemplate | 2000 /* Look for an existing WhereLoop to replace with pTemplate |
| 4143 */ | 2001 */ |
| 4144 whereLoopAdjustCost(pWInfo->pLoops, pTemplate); | 2002 whereLoopAdjustCost(pWInfo->pLoops, pTemplate); |
| 4145 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); | 2003 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate); |
| 4146 | 2004 |
| 4147 if( ppPrev==0 ){ | 2005 if( ppPrev==0 ){ |
| 4148 /* There already exists a WhereLoop on the list that is better | 2006 /* There already exists a WhereLoop on the list that is better |
| (...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 4206 p->u.btree.pIndex = 0; | 2064 p->u.btree.pIndex = 0; |
| 4207 } | 2065 } |
| 4208 } | 2066 } |
| 4209 return SQLITE_OK; | 2067 return SQLITE_OK; |
| 4210 } | 2068 } |
| 4211 | 2069 |
| 4212 /* | 2070 /* |
| 4213 ** Adjust the WhereLoop.nOut value downward to account for terms of the | 2071 ** Adjust the WhereLoop.nOut value downward to account for terms of the |
| 4214 ** WHERE clause that reference the loop but which are not used by an | 2072 ** WHERE clause that reference the loop but which are not used by an |
| 4215 ** index. | 2073 ** index. |
| 2074 * |
| 2075 ** For every WHERE clause term that is not used by the index |
| 2076 ** and which has a truth probability assigned by one of the likelihood(), |
| 2077 ** likely(), or unlikely() SQL functions, reduce the estimated number |
| 2078 ** of output rows by the probability specified. |
| 4216 ** | 2079 ** |
| 4217 ** In the current implementation, the first extra WHERE clause term reduces | 2080 ** TUNING: For every WHERE clause term that is not used by the index |
| 4218 ** the number of output rows by a factor of 10 and each additional term | 2081 ** and which does not have an assigned truth probability, heuristics |
| 4219 ** reduces the number of output rows by sqrt(2). | 2082 ** described below are used to try to estimate the truth probability. |
| 2083 ** TODO --> Perhaps this is something that could be improved by better |
| 2084 ** table statistics. |
| 2085 ** |
| 2086 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75% |
| 2087 ** value corresponds to -1 in LogEst notation, so this means decrement |
| 2088 ** the WhereLoop.nOut field for every such WHERE clause term. |
| 2089 ** |
| 2090 ** Heuristic 2: If there exists one or more WHERE clause terms of the |
| 2091 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the |
| 2092 ** final output row estimate is no greater than 1/4 of the total number |
| 2093 ** of rows in the table. In other words, assume that x==EXPR will filter |
| 2094 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the |
| 2095 ** "x" column is boolean or else -1 or 0 or 1 is a common default value |
| 2096 ** on the "x" column and so in that case only cap the output row estimate |
| 2097 ** at 1/2 instead of 1/4. |
| 4220 */ | 2098 */ |
| 4221 static void whereLoopOutputAdjust( | 2099 static void whereLoopOutputAdjust( |
| 4222 WhereClause *pWC, /* The WHERE clause */ | 2100 WhereClause *pWC, /* The WHERE clause */ |
| 4223 WhereLoop *pLoop, /* The loop to adjust downward */ | 2101 WhereLoop *pLoop, /* The loop to adjust downward */ |
| 4224 LogEst nRow /* Number of rows in the entire table */ | 2102 LogEst nRow /* Number of rows in the entire table */ |
| 4225 ){ | 2103 ){ |
| 4226 WhereTerm *pTerm, *pX; | 2104 WhereTerm *pTerm, *pX; |
| 4227 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); | 2105 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf); |
| 4228 int i, j; | 2106 int i, j, k; |
| 4229 int nEq = 0; /* Number of = constraints not within likely()/unlikely() */ | 2107 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */ |
| 4230 | 2108 |
| 2109 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 ); |
| 4231 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ | 2110 for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){ |
| 4232 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; | 2111 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break; |
| 4233 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; | 2112 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue; |
| 4234 if( (pTerm->prereqAll & notAllowed)!=0 ) continue; | 2113 if( (pTerm->prereqAll & notAllowed)!=0 ) continue; |
| 4235 for(j=pLoop->nLTerm-1; j>=0; j--){ | 2114 for(j=pLoop->nLTerm-1; j>=0; j--){ |
| 4236 pX = pLoop->aLTerm[j]; | 2115 pX = pLoop->aLTerm[j]; |
| 4237 if( pX==0 ) continue; | 2116 if( pX==0 ) continue; |
| 4238 if( pX==pTerm ) break; | 2117 if( pX==pTerm ) break; |
| 4239 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; | 2118 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break; |
| 4240 } | 2119 } |
| 4241 if( j<0 ){ | 2120 if( j<0 ){ |
| 4242 if( pTerm->truthProb<=0 ){ | 2121 if( pTerm->truthProb<=0 ){ |
| 2122 /* If a truth probability is specified using the likelihood() hints, |
| 2123 ** then use the probability provided by the application. */ |
| 4243 pLoop->nOut += pTerm->truthProb; | 2124 pLoop->nOut += pTerm->truthProb; |
| 4244 }else{ | 2125 }else{ |
| 2126 /* In the absence of explicit truth probabilities, use heuristics to |
| 2127 ** guess a reasonable truth probability. */ |
| 4245 pLoop->nOut--; | 2128 pLoop->nOut--; |
| 4246 if( pTerm->eOperator&WO_EQ ) nEq++; | 2129 if( pTerm->eOperator&(WO_EQ|WO_IS) ){ |
| 2130 Expr *pRight = pTerm->pExpr->pRight; |
| 2131 testcase( pTerm->pExpr->op==TK_IS ); |
| 2132 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){ |
| 2133 k = 10; |
| 2134 }else{ |
| 2135 k = 20; |
| 2136 } |
| 2137 if( iReduce<k ) iReduce = k; |
| 2138 } |
| 4247 } | 2139 } |
| 4248 } | 2140 } |
| 4249 } | 2141 } |
| 4250 /* TUNING: If there is at least one equality constraint in the WHERE | 2142 if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce; |
| 4251 ** clause that does not have a likelihood() explicitly assigned to it | |
| 4252 ** then do not let the estimated number of output rows exceed half | |
| 4253 ** the number of rows in the table. */ | |
| 4254 if( nEq && pLoop->nOut>nRow-10 ){ | |
| 4255 pLoop->nOut = nRow - 10; | |
| 4256 } | |
| 4257 } | 2143 } |
| 4258 | 2144 |
| 4259 /* | 2145 /* |
| 4260 ** Adjust the cost C by the costMult facter T. This only occurs if | 2146 ** Adjust the cost C by the costMult facter T. This only occurs if |
| 4261 ** compiled with -DSQLITE_ENABLE_COSTMULT | 2147 ** compiled with -DSQLITE_ENABLE_COSTMULT |
| 4262 */ | 2148 */ |
| 4263 #ifdef SQLITE_ENABLE_COSTMULT | 2149 #ifdef SQLITE_ENABLE_COSTMULT |
| 4264 # define ApplyCostMultiplier(C,T) C += T | 2150 # define ApplyCostMultiplier(C,T) C += T |
| 4265 #else | 2151 #else |
| 4266 # define ApplyCostMultiplier(C,T) | 2152 # define ApplyCostMultiplier(C,T) |
| (...skipping 20 matching lines...) Expand all Loading... |
| 4287 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ | 2173 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */ |
| 4288 Parse *pParse = pWInfo->pParse; /* Parsing context */ | 2174 Parse *pParse = pWInfo->pParse; /* Parsing context */ |
| 4289 sqlite3 *db = pParse->db; /* Database connection malloc context */ | 2175 sqlite3 *db = pParse->db; /* Database connection malloc context */ |
| 4290 WhereLoop *pNew; /* Template WhereLoop under construction */ | 2176 WhereLoop *pNew; /* Template WhereLoop under construction */ |
| 4291 WhereTerm *pTerm; /* A WhereTerm under consideration */ | 2177 WhereTerm *pTerm; /* A WhereTerm under consideration */ |
| 4292 int opMask; /* Valid operators for constraints */ | 2178 int opMask; /* Valid operators for constraints */ |
| 4293 WhereScan scan; /* Iterator for WHERE terms */ | 2179 WhereScan scan; /* Iterator for WHERE terms */ |
| 4294 Bitmask saved_prereq; /* Original value of pNew->prereq */ | 2180 Bitmask saved_prereq; /* Original value of pNew->prereq */ |
| 4295 u16 saved_nLTerm; /* Original value of pNew->nLTerm */ | 2181 u16 saved_nLTerm; /* Original value of pNew->nLTerm */ |
| 4296 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */ | 2182 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */ |
| 4297 u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */ | 2183 u16 saved_nSkip; /* Original value of pNew->nSkip */ |
| 4298 u32 saved_wsFlags; /* Original value of pNew->wsFlags */ | 2184 u32 saved_wsFlags; /* Original value of pNew->wsFlags */ |
| 4299 LogEst saved_nOut; /* Original value of pNew->nOut */ | 2185 LogEst saved_nOut; /* Original value of pNew->nOut */ |
| 4300 int iCol; /* Index of the column in the table */ | |
| 4301 int rc = SQLITE_OK; /* Return code */ | 2186 int rc = SQLITE_OK; /* Return code */ |
| 4302 LogEst rSize; /* Number of rows in the table */ | 2187 LogEst rSize; /* Number of rows in the table */ |
| 4303 LogEst rLogSize; /* Logarithm of table size */ | 2188 LogEst rLogSize; /* Logarithm of table size */ |
| 4304 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ | 2189 WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */ |
| 4305 | 2190 |
| 4306 pNew = pBuilder->pNew; | 2191 pNew = pBuilder->pNew; |
| 4307 if( db->mallocFailed ) return SQLITE_NOMEM; | 2192 if( db->mallocFailed ) return SQLITE_NOMEM; |
| 4308 | 2193 |
| 4309 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); | 2194 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 ); |
| 4310 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); | 2195 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 ); |
| 4311 if( pNew->wsFlags & WHERE_BTM_LIMIT ){ | 2196 if( pNew->wsFlags & WHERE_BTM_LIMIT ){ |
| 4312 opMask = WO_LT|WO_LE; | 2197 opMask = WO_LT|WO_LE; |
| 4313 }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){ | 2198 }else if( /*pProbe->tnum<=0 ||*/ (pSrc->fg.jointype & JT_LEFT)!=0 ){ |
| 4314 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE; | 2199 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE; |
| 4315 }else{ | 2200 }else{ |
| 4316 opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE; | 2201 opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS; |
| 4317 } | 2202 } |
| 4318 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); | 2203 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE); |
| 4319 | 2204 |
| 4320 assert( pNew->u.btree.nEq<pProbe->nColumn ); | 2205 assert( pNew->u.btree.nEq<pProbe->nColumn ); |
| 4321 iCol = pProbe->aiColumn[pNew->u.btree.nEq]; | |
| 4322 | 2206 |
| 4323 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol, | |
| 4324 opMask, pProbe); | |
| 4325 saved_nEq = pNew->u.btree.nEq; | 2207 saved_nEq = pNew->u.btree.nEq; |
| 4326 saved_nSkip = pNew->u.btree.nSkip; | 2208 saved_nSkip = pNew->nSkip; |
| 4327 saved_nLTerm = pNew->nLTerm; | 2209 saved_nLTerm = pNew->nLTerm; |
| 4328 saved_wsFlags = pNew->wsFlags; | 2210 saved_wsFlags = pNew->wsFlags; |
| 4329 saved_prereq = pNew->prereq; | 2211 saved_prereq = pNew->prereq; |
| 4330 saved_nOut = pNew->nOut; | 2212 saved_nOut = pNew->nOut; |
| 2213 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq, |
| 2214 opMask, pProbe); |
| 4331 pNew->rSetup = 0; | 2215 pNew->rSetup = 0; |
| 4332 rSize = pProbe->aiRowLogEst[0]; | 2216 rSize = pProbe->aiRowLogEst[0]; |
| 4333 rLogSize = estLog(rSize); | 2217 rLogSize = estLog(rSize); |
| 4334 | |
| 4335 /* Consider using a skip-scan if there are no WHERE clause constraints | |
| 4336 ** available for the left-most terms of the index, and if the average | |
| 4337 ** number of repeats in the left-most terms is at least 18. | |
| 4338 ** | |
| 4339 ** The magic number 18 is selected on the basis that scanning 17 rows | |
| 4340 ** is almost always quicker than an index seek (even though if the index | |
| 4341 ** contains fewer than 2^17 rows we assume otherwise in other parts of | |
| 4342 ** the code). And, even if it is not, it should not be too much slower. | |
| 4343 ** On the other hand, the extra seeks could end up being significantly | |
| 4344 ** more expensive. */ | |
| 4345 assert( 42==sqlite3LogEst(18) ); | |
| 4346 if( saved_nEq==saved_nSkip | |
| 4347 && saved_nEq+1<pProbe->nKeyCol | |
| 4348 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ | |
| 4349 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK | |
| 4350 ){ | |
| 4351 LogEst nIter; | |
| 4352 pNew->u.btree.nEq++; | |
| 4353 pNew->u.btree.nSkip++; | |
| 4354 pNew->aLTerm[pNew->nLTerm++] = 0; | |
| 4355 pNew->wsFlags |= WHERE_SKIPSCAN; | |
| 4356 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1]; | |
| 4357 if( pTerm ){ | |
| 4358 /* TUNING: When estimating skip-scan for a term that is also indexable, | |
| 4359 ** multiply the cost of the skip-scan by 2.0, to make it a little less | |
| 4360 ** desirable than the regular index lookup. */ | |
| 4361 nIter += 10; assert( 10==sqlite3LogEst(2) ); | |
| 4362 } | |
| 4363 pNew->nOut -= nIter; | |
| 4364 /* TUNING: Because uncertainties in the estimates for skip-scan queries, | |
| 4365 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */ | |
| 4366 nIter += 5; | |
| 4367 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul); | |
| 4368 pNew->nOut = saved_nOut; | |
| 4369 pNew->u.btree.nEq = saved_nEq; | |
| 4370 pNew->u.btree.nSkip = saved_nSkip; | |
| 4371 } | |
| 4372 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ | 2218 for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){ |
| 4373 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ | 2219 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */ |
| 4374 LogEst rCostIdx; | 2220 LogEst rCostIdx; |
| 4375 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ | 2221 LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */ |
| 4376 int nIn = 0; | 2222 int nIn = 0; |
| 4377 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | 2223 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
| 4378 int nRecValid = pBuilder->nRecValid; | 2224 int nRecValid = pBuilder->nRecValid; |
| 4379 #endif | 2225 #endif |
| 4380 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) | 2226 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0) |
| 4381 && (iCol<0 || pSrc->pTab->aCol[iCol].notNull) | 2227 && indexColumnNotNull(pProbe, saved_nEq) |
| 4382 ){ | 2228 ){ |
| 4383 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ | 2229 continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */ |
| 4384 } | 2230 } |
| 4385 if( pTerm->prereqRight & pNew->maskSelf ) continue; | 2231 if( pTerm->prereqRight & pNew->maskSelf ) continue; |
| 4386 | 2232 |
| 2233 /* Do not allow the upper bound of a LIKE optimization range constraint |
| 2234 ** to mix with a lower range bound from some other source */ |
| 2235 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue; |
| 2236 |
| 4387 pNew->wsFlags = saved_wsFlags; | 2237 pNew->wsFlags = saved_wsFlags; |
| 4388 pNew->u.btree.nEq = saved_nEq; | 2238 pNew->u.btree.nEq = saved_nEq; |
| 4389 pNew->nLTerm = saved_nLTerm; | 2239 pNew->nLTerm = saved_nLTerm; |
| 4390 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ | 2240 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ |
| 4391 pNew->aLTerm[pNew->nLTerm++] = pTerm; | 2241 pNew->aLTerm[pNew->nLTerm++] = pTerm; |
| 4392 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; | 2242 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf; |
| 4393 | 2243 |
| 4394 assert( nInMul==0 | 2244 assert( nInMul==0 |
| 4395 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 | 2245 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 |
| 4396 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 | 2246 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 |
| 4397 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 | 2247 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 |
| 4398 ); | 2248 ); |
| 4399 | 2249 |
| 4400 if( eOp & WO_IN ){ | 2250 if( eOp & WO_IN ){ |
| 4401 Expr *pExpr = pTerm->pExpr; | 2251 Expr *pExpr = pTerm->pExpr; |
| 4402 pNew->wsFlags |= WHERE_COLUMN_IN; | 2252 pNew->wsFlags |= WHERE_COLUMN_IN; |
| 4403 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ | 2253 if( ExprHasProperty(pExpr, EP_xIsSelect) ){ |
| 4404 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ | 2254 /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */ |
| 4405 nIn = 46; assert( 46==sqlite3LogEst(25) ); | 2255 nIn = 46; assert( 46==sqlite3LogEst(25) ); |
| 4406 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ | 2256 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){ |
| 4407 /* "x IN (value, value, ...)" */ | 2257 /* "x IN (value, value, ...)" */ |
| 4408 nIn = sqlite3LogEst(pExpr->x.pList->nExpr); | 2258 nIn = sqlite3LogEst(pExpr->x.pList->nExpr); |
| 4409 } | 2259 } |
| 4410 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser | 2260 assert( nIn>0 ); /* RHS always has 2 or more terms... The parser |
| 4411 ** changes "x IN (?)" into "x=?". */ | 2261 ** changes "x IN (?)" into "x=?". */ |
| 4412 | 2262 |
| 4413 }else if( eOp & (WO_EQ) ){ | 2263 }else if( eOp & (WO_EQ|WO_IS) ){ |
| 2264 int iCol = pProbe->aiColumn[saved_nEq]; |
| 4414 pNew->wsFlags |= WHERE_COLUMN_EQ; | 2265 pNew->wsFlags |= WHERE_COLUMN_EQ; |
| 4415 if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){ | 2266 assert( saved_nEq==pNew->u.btree.nEq ); |
| 4416 if( iCol>=0 && !IsUniqueIndex(pProbe) ){ | 2267 if( iCol==XN_ROWID |
| 2268 || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1) |
| 2269 ){ |
| 2270 if( iCol>=0 && pProbe->uniqNotNull==0 ){ |
| 4417 pNew->wsFlags |= WHERE_UNQ_WANTED; | 2271 pNew->wsFlags |= WHERE_UNQ_WANTED; |
| 4418 }else{ | 2272 }else{ |
| 4419 pNew->wsFlags |= WHERE_ONEROW; | 2273 pNew->wsFlags |= WHERE_ONEROW; |
| 4420 } | 2274 } |
| 4421 } | 2275 } |
| 4422 }else if( eOp & WO_ISNULL ){ | 2276 }else if( eOp & WO_ISNULL ){ |
| 4423 pNew->wsFlags |= WHERE_COLUMN_NULL; | 2277 pNew->wsFlags |= WHERE_COLUMN_NULL; |
| 4424 }else if( eOp & (WO_GT|WO_GE) ){ | 2278 }else if( eOp & (WO_GT|WO_GE) ){ |
| 4425 testcase( eOp & WO_GT ); | 2279 testcase( eOp & WO_GT ); |
| 4426 testcase( eOp & WO_GE ); | 2280 testcase( eOp & WO_GE ); |
| 4427 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; | 2281 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT; |
| 4428 pBtm = pTerm; | 2282 pBtm = pTerm; |
| 4429 pTop = 0; | 2283 pTop = 0; |
| 2284 if( pTerm->wtFlags & TERM_LIKEOPT ){ |
| 2285 /* Range contraints that come from the LIKE optimization are |
| 2286 ** always used in pairs. */ |
| 2287 pTop = &pTerm[1]; |
| 2288 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm ); |
| 2289 assert( pTop->wtFlags & TERM_LIKEOPT ); |
| 2290 assert( pTop->eOperator==WO_LT ); |
| 2291 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */ |
| 2292 pNew->aLTerm[pNew->nLTerm++] = pTop; |
| 2293 pNew->wsFlags |= WHERE_TOP_LIMIT; |
| 2294 } |
| 4430 }else{ | 2295 }else{ |
| 4431 assert( eOp & (WO_LT|WO_LE) ); | 2296 assert( eOp & (WO_LT|WO_LE) ); |
| 4432 testcase( eOp & WO_LT ); | 2297 testcase( eOp & WO_LT ); |
| 4433 testcase( eOp & WO_LE ); | 2298 testcase( eOp & WO_LE ); |
| 4434 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; | 2299 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT; |
| 4435 pTop = pTerm; | 2300 pTop = pTerm; |
| 4436 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? | 2301 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ? |
| 4437 pNew->aLTerm[pNew->nLTerm-2] : 0; | 2302 pNew->aLTerm[pNew->nLTerm-2] : 0; |
| 4438 } | 2303 } |
| 4439 | 2304 |
| 4440 /* At this point pNew->nOut is set to the number of rows expected to | 2305 /* At this point pNew->nOut is set to the number of rows expected to |
| 4441 ** be visited by the index scan before considering term pTerm, or the | 2306 ** be visited by the index scan before considering term pTerm, or the |
| 4442 ** values of nIn and nInMul. In other words, assuming that all | 2307 ** values of nIn and nInMul. In other words, assuming that all |
| 4443 ** "x IN(...)" terms are replaced with "x = ?". This block updates | 2308 ** "x IN(...)" terms are replaced with "x = ?". This block updates |
| 4444 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ | 2309 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */ |
| 4445 assert( pNew->nOut==saved_nOut ); | 2310 assert( pNew->nOut==saved_nOut ); |
| 4446 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ | 2311 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){ |
| 4447 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4 | 2312 /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4 |
| 4448 ** data, using some other estimate. */ | 2313 ** data, using some other estimate. */ |
| 4449 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); | 2314 whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew); |
| 4450 }else{ | 2315 }else{ |
| 4451 int nEq = ++pNew->u.btree.nEq; | 2316 int nEq = ++pNew->u.btree.nEq; |
| 4452 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) ); | 2317 assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) ); |
| 4453 | 2318 |
| 4454 assert( pNew->nOut==saved_nOut ); | 2319 assert( pNew->nOut==saved_nOut ); |
| 4455 if( pTerm->truthProb<=0 && iCol>=0 ){ | 2320 if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){ |
| 4456 assert( (eOp & WO_IN) || nIn==0 ); | 2321 assert( (eOp & WO_IN) || nIn==0 ); |
| 4457 testcase( eOp & WO_IN ); | 2322 testcase( eOp & WO_IN ); |
| 4458 pNew->nOut += pTerm->truthProb; | 2323 pNew->nOut += pTerm->truthProb; |
| 4459 pNew->nOut -= nIn; | 2324 pNew->nOut -= nIn; |
| 4460 }else{ | 2325 }else{ |
| 4461 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | 2326 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
| 4462 tRowcnt nOut = 0; | 2327 tRowcnt nOut = 0; |
| 4463 if( nInMul==0 | 2328 if( nInMul==0 |
| 4464 && pProbe->nSample | 2329 && pProbe->nSample |
| 4465 && pNew->u.btree.nEq<=pProbe->nSampleCol | 2330 && pNew->u.btree.nEq<=pProbe->nSampleCol |
| 4466 && OptimizationEnabled(db, SQLITE_Stat3) | |
| 4467 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) | 2331 && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect)) |
| 4468 ){ | 2332 ){ |
| 4469 Expr *pExpr = pTerm->pExpr; | 2333 Expr *pExpr = pTerm->pExpr; |
| 4470 if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){ | 2334 if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){ |
| 4471 testcase( eOp & WO_EQ ); | 2335 testcase( eOp & WO_EQ ); |
| 2336 testcase( eOp & WO_IS ); |
| 4472 testcase( eOp & WO_ISNULL ); | 2337 testcase( eOp & WO_ISNULL ); |
| 4473 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); | 2338 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut); |
| 4474 }else{ | 2339 }else{ |
| 4475 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); | 2340 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut); |
| 4476 } | 2341 } |
| 4477 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; | 2342 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK; |
| 4478 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ | 2343 if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */ |
| 4479 if( nOut ){ | 2344 if( nOut ){ |
| 4480 pNew->nOut = sqlite3LogEst(nOut); | 2345 pNew->nOut = sqlite3LogEst(nOut); |
| 4481 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; | 2346 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut; |
| (...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 4524 ){ | 2389 ){ |
| 4525 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); | 2390 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn); |
| 4526 } | 2391 } |
| 4527 pNew->nOut = saved_nOut; | 2392 pNew->nOut = saved_nOut; |
| 4528 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | 2393 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
| 4529 pBuilder->nRecValid = nRecValid; | 2394 pBuilder->nRecValid = nRecValid; |
| 4530 #endif | 2395 #endif |
| 4531 } | 2396 } |
| 4532 pNew->prereq = saved_prereq; | 2397 pNew->prereq = saved_prereq; |
| 4533 pNew->u.btree.nEq = saved_nEq; | 2398 pNew->u.btree.nEq = saved_nEq; |
| 4534 pNew->u.btree.nSkip = saved_nSkip; | 2399 pNew->nSkip = saved_nSkip; |
| 4535 pNew->wsFlags = saved_wsFlags; | 2400 pNew->wsFlags = saved_wsFlags; |
| 4536 pNew->nOut = saved_nOut; | 2401 pNew->nOut = saved_nOut; |
| 4537 pNew->nLTerm = saved_nLTerm; | 2402 pNew->nLTerm = saved_nLTerm; |
| 2403 |
| 2404 /* Consider using a skip-scan if there are no WHERE clause constraints |
| 2405 ** available for the left-most terms of the index, and if the average |
| 2406 ** number of repeats in the left-most terms is at least 18. |
| 2407 ** |
| 2408 ** The magic number 18 is selected on the basis that scanning 17 rows |
| 2409 ** is almost always quicker than an index seek (even though if the index |
| 2410 ** contains fewer than 2^17 rows we assume otherwise in other parts of |
| 2411 ** the code). And, even if it is not, it should not be too much slower. |
| 2412 ** On the other hand, the extra seeks could end up being significantly |
| 2413 ** more expensive. */ |
| 2414 assert( 42==sqlite3LogEst(18) ); |
| 2415 if( saved_nEq==saved_nSkip |
| 2416 && saved_nEq+1<pProbe->nKeyCol |
| 2417 && pProbe->noSkipScan==0 |
| 2418 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */ |
| 2419 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK |
| 2420 ){ |
| 2421 LogEst nIter; |
| 2422 pNew->u.btree.nEq++; |
| 2423 pNew->nSkip++; |
| 2424 pNew->aLTerm[pNew->nLTerm++] = 0; |
| 2425 pNew->wsFlags |= WHERE_SKIPSCAN; |
| 2426 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1]; |
| 2427 pNew->nOut -= nIter; |
| 2428 /* TUNING: Because uncertainties in the estimates for skip-scan queries, |
| 2429 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */ |
| 2430 nIter += 5; |
| 2431 whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul); |
| 2432 pNew->nOut = saved_nOut; |
| 2433 pNew->u.btree.nEq = saved_nEq; |
| 2434 pNew->nSkip = saved_nSkip; |
| 2435 pNew->wsFlags = saved_wsFlags; |
| 2436 } |
| 2437 |
| 4538 return rc; | 2438 return rc; |
| 4539 } | 2439 } |
| 4540 | 2440 |
| 4541 /* | 2441 /* |
| 4542 ** Return True if it is possible that pIndex might be useful in | 2442 ** Return True if it is possible that pIndex might be useful in |
| 4543 ** implementing the ORDER BY clause in pBuilder. | 2443 ** implementing the ORDER BY clause in pBuilder. |
| 4544 ** | 2444 ** |
| 4545 ** Return False if pBuilder does not contain an ORDER BY clause or | 2445 ** Return False if pBuilder does not contain an ORDER BY clause or |
| 4546 ** if there is no way for pIndex to be useful in implementing that | 2446 ** if there is no way for pIndex to be useful in implementing that |
| 4547 ** ORDER BY clause. | 2447 ** ORDER BY clause. |
| 4548 */ | 2448 */ |
| 4549 static int indexMightHelpWithOrderBy( | 2449 static int indexMightHelpWithOrderBy( |
| 4550 WhereLoopBuilder *pBuilder, | 2450 WhereLoopBuilder *pBuilder, |
| 4551 Index *pIndex, | 2451 Index *pIndex, |
| 4552 int iCursor | 2452 int iCursor |
| 4553 ){ | 2453 ){ |
| 4554 ExprList *pOB; | 2454 ExprList *pOB; |
| 2455 ExprList *aColExpr; |
| 4555 int ii, jj; | 2456 int ii, jj; |
| 4556 | 2457 |
| 4557 if( pIndex->bUnordered ) return 0; | 2458 if( pIndex->bUnordered ) return 0; |
| 4558 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; | 2459 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0; |
| 4559 for(ii=0; ii<pOB->nExpr; ii++){ | 2460 for(ii=0; ii<pOB->nExpr; ii++){ |
| 4560 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); | 2461 Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr); |
| 4561 if( pExpr->op!=TK_COLUMN ) return 0; | 2462 if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){ |
| 4562 if( pExpr->iTable==iCursor ){ | |
| 4563 if( pExpr->iColumn<0 ) return 1; | 2463 if( pExpr->iColumn<0 ) return 1; |
| 4564 for(jj=0; jj<pIndex->nKeyCol; jj++){ | 2464 for(jj=0; jj<pIndex->nKeyCol; jj++){ |
| 4565 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; | 2465 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1; |
| 4566 } | 2466 } |
| 2467 }else if( (aColExpr = pIndex->aColExpr)!=0 ){ |
| 2468 for(jj=0; jj<pIndex->nKeyCol; jj++){ |
| 2469 if( pIndex->aiColumn[jj]!=XN_EXPR ) continue; |
| 2470 if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){ |
| 2471 return 1; |
| 2472 } |
| 2473 } |
| 4567 } | 2474 } |
| 4568 } | 2475 } |
| 4569 return 0; | 2476 return 0; |
| 4570 } | 2477 } |
| 4571 | 2478 |
| 4572 /* | 2479 /* |
| 4573 ** Return a bitmask where 1s indicate that the corresponding column of | 2480 ** Return a bitmask where 1s indicate that the corresponding column of |
| 4574 ** the table is used by an index. Only the first 63 columns are considered. | 2481 ** the table is used by an index. Only the first 63 columns are considered. |
| 4575 */ | 2482 */ |
| 4576 static Bitmask columnsInIndex(Index *pIdx){ | 2483 static Bitmask columnsInIndex(Index *pIdx){ |
| 4577 Bitmask m = 0; | 2484 Bitmask m = 0; |
| 4578 int j; | 2485 int j; |
| 4579 for(j=pIdx->nColumn-1; j>=0; j--){ | 2486 for(j=pIdx->nColumn-1; j>=0; j--){ |
| 4580 int x = pIdx->aiColumn[j]; | 2487 int x = pIdx->aiColumn[j]; |
| 4581 if( x>=0 ){ | 2488 if( x>=0 ){ |
| 4582 testcase( x==BMS-1 ); | 2489 testcase( x==BMS-1 ); |
| 4583 testcase( x==BMS-2 ); | 2490 testcase( x==BMS-2 ); |
| 4584 if( x<BMS-1 ) m |= MASKBIT(x); | 2491 if( x<BMS-1 ) m |= MASKBIT(x); |
| 4585 } | 2492 } |
| 4586 } | 2493 } |
| 4587 return m; | 2494 return m; |
| 4588 } | 2495 } |
| 4589 | 2496 |
| 4590 /* Check to see if a partial index with pPartIndexWhere can be used | 2497 /* Check to see if a partial index with pPartIndexWhere can be used |
| 4591 ** in the current query. Return true if it can be and false if not. | 2498 ** in the current query. Return true if it can be and false if not. |
| 4592 */ | 2499 */ |
| 4593 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){ | 2500 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){ |
| 4594 int i; | 2501 int i; |
| 4595 WhereTerm *pTerm; | 2502 WhereTerm *pTerm; |
| 2503 while( pWhere->op==TK_AND ){ |
| 2504 if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0; |
| 2505 pWhere = pWhere->pRight; |
| 2506 } |
| 4596 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ | 2507 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){ |
| 4597 if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1; | 2508 Expr *pExpr = pTerm->pExpr; |
| 2509 if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab) |
| 2510 && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab) |
| 2511 ){ |
| 2512 return 1; |
| 2513 } |
| 4598 } | 2514 } |
| 4599 return 0; | 2515 return 0; |
| 4600 } | 2516 } |
| 4601 | 2517 |
| 4602 /* | 2518 /* |
| 4603 ** Add all WhereLoop objects for a single table of the join where the table | 2519 ** Add all WhereLoop objects for a single table of the join where the table |
| 4604 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be | 2520 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be |
| 4605 ** a b-tree table, not a virtual table. | 2521 ** a b-tree table, not a virtual table. |
| 4606 ** | 2522 ** |
| 4607 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function | 2523 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function |
| (...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 4656 Table *pTab; /* Table being queried */ | 2572 Table *pTab; /* Table being queried */ |
| 4657 | 2573 |
| 4658 pNew = pBuilder->pNew; | 2574 pNew = pBuilder->pNew; |
| 4659 pWInfo = pBuilder->pWInfo; | 2575 pWInfo = pBuilder->pWInfo; |
| 4660 pTabList = pWInfo->pTabList; | 2576 pTabList = pWInfo->pTabList; |
| 4661 pSrc = pTabList->a + pNew->iTab; | 2577 pSrc = pTabList->a + pNew->iTab; |
| 4662 pTab = pSrc->pTab; | 2578 pTab = pSrc->pTab; |
| 4663 pWC = pBuilder->pWC; | 2579 pWC = pBuilder->pWC; |
| 4664 assert( !IsVirtual(pSrc->pTab) ); | 2580 assert( !IsVirtual(pSrc->pTab) ); |
| 4665 | 2581 |
| 4666 if( pSrc->pIndex ){ | 2582 if( pSrc->pIBIndex ){ |
| 4667 /* An INDEXED BY clause specifies a particular index to use */ | 2583 /* An INDEXED BY clause specifies a particular index to use */ |
| 4668 pProbe = pSrc->pIndex; | 2584 pProbe = pSrc->pIBIndex; |
| 4669 }else if( !HasRowid(pTab) ){ | 2585 }else if( !HasRowid(pTab) ){ |
| 4670 pProbe = pTab->pIndex; | 2586 pProbe = pTab->pIndex; |
| 4671 }else{ | 2587 }else{ |
| 4672 /* There is no INDEXED BY clause. Create a fake Index object in local | 2588 /* There is no INDEXED BY clause. Create a fake Index object in local |
| 4673 ** variable sPk to represent the rowid primary key index. Make this | 2589 ** variable sPk to represent the rowid primary key index. Make this |
| 4674 ** fake index the first in a chain of Index objects with all of the real | 2590 ** fake index the first in a chain of Index objects with all of the real |
| 4675 ** indices to follow */ | 2591 ** indices to follow */ |
| 4676 Index *pFirst; /* First of real indices on the table */ | 2592 Index *pFirst; /* First of real indices on the table */ |
| 4677 memset(&sPk, 0, sizeof(Index)); | 2593 memset(&sPk, 0, sizeof(Index)); |
| 4678 sPk.nKeyCol = 1; | 2594 sPk.nKeyCol = 1; |
| 4679 sPk.nColumn = 1; | 2595 sPk.nColumn = 1; |
| 4680 sPk.aiColumn = &aiColumnPk; | 2596 sPk.aiColumn = &aiColumnPk; |
| 4681 sPk.aiRowLogEst = aiRowEstPk; | 2597 sPk.aiRowLogEst = aiRowEstPk; |
| 4682 sPk.onError = OE_Replace; | 2598 sPk.onError = OE_Replace; |
| 4683 sPk.pTable = pTab; | 2599 sPk.pTable = pTab; |
| 4684 sPk.szIdxRow = pTab->szTabRow; | 2600 sPk.szIdxRow = pTab->szTabRow; |
| 4685 aiRowEstPk[0] = pTab->nRowLogEst; | 2601 aiRowEstPk[0] = pTab->nRowLogEst; |
| 4686 aiRowEstPk[1] = 0; | 2602 aiRowEstPk[1] = 0; |
| 4687 pFirst = pSrc->pTab->pIndex; | 2603 pFirst = pSrc->pTab->pIndex; |
| 4688 if( pSrc->notIndexed==0 ){ | 2604 if( pSrc->fg.notIndexed==0 ){ |
| 4689 /* The real indices of the table are only considered if the | 2605 /* The real indices of the table are only considered if the |
| 4690 ** NOT INDEXED qualifier is omitted from the FROM clause */ | 2606 ** NOT INDEXED qualifier is omitted from the FROM clause */ |
| 4691 sPk.pNext = pFirst; | 2607 sPk.pNext = pFirst; |
| 4692 } | 2608 } |
| 4693 pProbe = &sPk; | 2609 pProbe = &sPk; |
| 4694 } | 2610 } |
| 4695 rSize = pTab->nRowLogEst; | 2611 rSize = pTab->nRowLogEst; |
| 4696 rLogSize = estLog(rSize); | 2612 rLogSize = estLog(rSize); |
| 4697 | 2613 |
| 4698 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX | 2614 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX |
| 4699 /* Automatic indexes */ | 2615 /* Automatic indexes */ |
| 4700 if( !pBuilder->pOrSet | 2616 if( !pBuilder->pOrSet /* Not part of an OR optimization */ |
| 2617 && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0 |
| 4701 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 | 2618 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0 |
| 4702 && pSrc->pIndex==0 | 2619 && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */ |
| 4703 && !pSrc->viaCoroutine | 2620 && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */ |
| 4704 && !pSrc->notIndexed | 2621 && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */ |
| 4705 && HasRowid(pTab) | 2622 && !pSrc->fg.isCorrelated /* Not a correlated subquery */ |
| 4706 && !pSrc->isCorrelated | 2623 && !pSrc->fg.isRecursive /* Not a recursive common table expression. */ |
| 4707 && !pSrc->isRecursive | |
| 4708 ){ | 2624 ){ |
| 4709 /* Generate auto-index WhereLoops */ | 2625 /* Generate auto-index WhereLoops */ |
| 4710 WhereTerm *pTerm; | 2626 WhereTerm *pTerm; |
| 4711 WhereTerm *pWCEnd = pWC->a + pWC->nTerm; | 2627 WhereTerm *pWCEnd = pWC->a + pWC->nTerm; |
| 4712 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){ | 2628 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){ |
| 4713 if( pTerm->prereqRight & pNew->maskSelf ) continue; | 2629 if( pTerm->prereqRight & pNew->maskSelf ) continue; |
| 4714 if( termCanDriveIndex(pTerm, pSrc, 0) ){ | 2630 if( termCanDriveIndex(pTerm, pSrc, 0) ){ |
| 4715 pNew->u.btree.nEq = 1; | 2631 pNew->u.btree.nEq = 1; |
| 4716 pNew->u.btree.nSkip = 0; | 2632 pNew->nSkip = 0; |
| 4717 pNew->u.btree.pIndex = 0; | 2633 pNew->u.btree.pIndex = 0; |
| 4718 pNew->nLTerm = 1; | 2634 pNew->nLTerm = 1; |
| 4719 pNew->aLTerm[0] = pTerm; | 2635 pNew->aLTerm[0] = pTerm; |
| 4720 /* TUNING: One-time cost for computing the automatic index is | 2636 /* TUNING: One-time cost for computing the automatic index is |
| 4721 ** estimated to be X*N*log2(N) where N is the number of rows in | 2637 ** estimated to be X*N*log2(N) where N is the number of rows in |
| 4722 ** the table being indexed and where X is 7 (LogEst=28) for normal | 2638 ** the table being indexed and where X is 7 (LogEst=28) for normal |
| 4723 ** tables or 1.375 (LogEst=4) for views and subqueries. The value | 2639 ** tables or 1.375 (LogEst=4) for views and subqueries. The value |
| 4724 ** of X is smaller for views and subqueries so that the query planner | 2640 ** of X is smaller for views and subqueries so that the query planner |
| 4725 ** will be more aggressive about generating automatic indexes for | 2641 ** will be more aggressive about generating automatic indexes for |
| 4726 ** those objects, since there is no opportunity to add schema | 2642 ** those objects, since there is no opportunity to add schema |
| (...skipping 20 matching lines...) Expand all Loading... |
| 4747 /* Loop over all indices | 2663 /* Loop over all indices |
| 4748 */ | 2664 */ |
| 4749 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ | 2665 for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){ |
| 4750 if( pProbe->pPartIdxWhere!=0 | 2666 if( pProbe->pPartIdxWhere!=0 |
| 4751 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){ | 2667 && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){ |
| 4752 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ | 2668 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */ |
| 4753 continue; /* Partial index inappropriate for this query */ | 2669 continue; /* Partial index inappropriate for this query */ |
| 4754 } | 2670 } |
| 4755 rSize = pProbe->aiRowLogEst[0]; | 2671 rSize = pProbe->aiRowLogEst[0]; |
| 4756 pNew->u.btree.nEq = 0; | 2672 pNew->u.btree.nEq = 0; |
| 4757 pNew->u.btree.nSkip = 0; | 2673 pNew->nSkip = 0; |
| 4758 pNew->nLTerm = 0; | 2674 pNew->nLTerm = 0; |
| 4759 pNew->iSortIdx = 0; | 2675 pNew->iSortIdx = 0; |
| 4760 pNew->rSetup = 0; | 2676 pNew->rSetup = 0; |
| 4761 pNew->prereq = mExtra; | 2677 pNew->prereq = mExtra; |
| 4762 pNew->nOut = rSize; | 2678 pNew->nOut = rSize; |
| 4763 pNew->u.btree.pIndex = pProbe; | 2679 pNew->u.btree.pIndex = pProbe; |
| 4764 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); | 2680 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor); |
| 4765 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ | 2681 /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */ |
| 4766 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); | 2682 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 ); |
| 4767 if( pProbe->tnum<=0 ){ | 2683 if( pProbe->tnum<=0 ){ |
| (...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 4818 | 2734 |
| 4819 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); | 2735 rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0); |
| 4820 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 | 2736 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4 |
| 4821 sqlite3Stat4ProbeFree(pBuilder->pRec); | 2737 sqlite3Stat4ProbeFree(pBuilder->pRec); |
| 4822 pBuilder->nRecValid = 0; | 2738 pBuilder->nRecValid = 0; |
| 4823 pBuilder->pRec = 0; | 2739 pBuilder->pRec = 0; |
| 4824 #endif | 2740 #endif |
| 4825 | 2741 |
| 4826 /* If there was an INDEXED BY clause, then only that one index is | 2742 /* If there was an INDEXED BY clause, then only that one index is |
| 4827 ** considered. */ | 2743 ** considered. */ |
| 4828 if( pSrc->pIndex ) break; | 2744 if( pSrc->pIBIndex ) break; |
| 4829 } | 2745 } |
| 4830 return rc; | 2746 return rc; |
| 4831 } | 2747 } |
| 4832 | 2748 |
| 4833 #ifndef SQLITE_OMIT_VIRTUALTABLE | 2749 #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 4834 /* | 2750 /* |
| 4835 ** Add all WhereLoop objects for a table of the join identified by | 2751 ** Add all WhereLoop objects for a table of the join identified by |
| 4836 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. | 2752 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table. |
| 2753 ** |
| 2754 ** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and |
| 2755 ** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause |
| 2756 ** entries that occur before the virtual table in the FROM clause and are |
| 2757 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the |
| 2758 ** mUnusable mask contains all FROM clause entries that occur after the |
| 2759 ** virtual table and are separated from it by at least one LEFT or |
| 2760 ** CROSS JOIN. |
| 2761 ** |
| 2762 ** For example, if the query were: |
| 2763 ** |
| 2764 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6; |
| 2765 ** |
| 2766 ** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6). |
| 2767 ** |
| 2768 ** All the tables in mExtra must be scanned before the current virtual |
| 2769 ** table. So any terms for which all prerequisites are satisfied by |
| 2770 ** mExtra may be specified as "usable" in all calls to xBestIndex. |
| 2771 ** Conversely, all tables in mUnusable must be scanned after the current |
| 2772 ** virtual table, so any terms for which the prerequisites overlap with |
| 2773 ** mUnusable should always be configured as "not-usable" for xBestIndex. |
| 4837 */ | 2774 */ |
| 4838 static int whereLoopAddVirtual( | 2775 static int whereLoopAddVirtual( |
| 4839 WhereLoopBuilder *pBuilder, /* WHERE clause information */ | 2776 WhereLoopBuilder *pBuilder, /* WHERE clause information */ |
| 4840 Bitmask mExtra | 2777 Bitmask mExtra, /* Tables that must be scanned before this one */ |
| 2778 Bitmask mUnusable /* Tables that must be scanned after this one */ |
| 4841 ){ | 2779 ){ |
| 4842 WhereInfo *pWInfo; /* WHERE analysis context */ | 2780 WhereInfo *pWInfo; /* WHERE analysis context */ |
| 4843 Parse *pParse; /* The parsing context */ | 2781 Parse *pParse; /* The parsing context */ |
| 4844 WhereClause *pWC; /* The WHERE clause */ | 2782 WhereClause *pWC; /* The WHERE clause */ |
| 4845 struct SrcList_item *pSrc; /* The FROM clause term to search */ | 2783 struct SrcList_item *pSrc; /* The FROM clause term to search */ |
| 4846 Table *pTab; | 2784 Table *pTab; |
| 4847 sqlite3 *db; | 2785 sqlite3 *db; |
| 4848 sqlite3_index_info *pIdxInfo; | 2786 sqlite3_index_info *pIdxInfo; |
| 4849 struct sqlite3_index_constraint *pIdxCons; | 2787 struct sqlite3_index_constraint *pIdxCons; |
| 4850 struct sqlite3_index_constraint_usage *pUsage; | 2788 struct sqlite3_index_constraint_usage *pUsage; |
| 4851 WhereTerm *pTerm; | 2789 WhereTerm *pTerm; |
| 4852 int i, j; | 2790 int i, j; |
| 4853 int iTerm, mxTerm; | 2791 int iTerm, mxTerm; |
| 4854 int nConstraint; | 2792 int nConstraint; |
| 4855 int seenIn = 0; /* True if an IN operator is seen */ | 2793 int seenIn = 0; /* True if an IN operator is seen */ |
| 4856 int seenVar = 0; /* True if a non-constant constraint is seen */ | 2794 int seenVar = 0; /* True if a non-constant constraint is seen */ |
| 4857 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */ | 2795 int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */ |
| 4858 WhereLoop *pNew; | 2796 WhereLoop *pNew; |
| 4859 int rc = SQLITE_OK; | 2797 int rc = SQLITE_OK; |
| 4860 | 2798 |
| 2799 assert( (mExtra & mUnusable)==0 ); |
| 4861 pWInfo = pBuilder->pWInfo; | 2800 pWInfo = pBuilder->pWInfo; |
| 4862 pParse = pWInfo->pParse; | 2801 pParse = pWInfo->pParse; |
| 4863 db = pParse->db; | 2802 db = pParse->db; |
| 4864 pWC = pBuilder->pWC; | 2803 pWC = pBuilder->pWC; |
| 4865 pNew = pBuilder->pNew; | 2804 pNew = pBuilder->pNew; |
| 4866 pSrc = &pWInfo->pTabList->a[pNew->iTab]; | 2805 pSrc = &pWInfo->pTabList->a[pNew->iTab]; |
| 4867 pTab = pSrc->pTab; | 2806 pTab = pSrc->pTab; |
| 4868 assert( IsVirtual(pTab) ); | 2807 assert( IsVirtual(pTab) ); |
| 4869 pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy); | 2808 pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy); |
| 4870 if( pIdxInfo==0 ) return SQLITE_NOMEM; | 2809 if( pIdxInfo==0 ) return SQLITE_NOMEM; |
| 4871 pNew->prereq = 0; | 2810 pNew->prereq = 0; |
| 4872 pNew->rSetup = 0; | 2811 pNew->rSetup = 0; |
| 4873 pNew->wsFlags = WHERE_VIRTUALTABLE; | 2812 pNew->wsFlags = WHERE_VIRTUALTABLE; |
| 4874 pNew->nLTerm = 0; | 2813 pNew->nLTerm = 0; |
| 4875 pNew->u.vtab.needFree = 0; | 2814 pNew->u.vtab.needFree = 0; |
| 4876 pUsage = pIdxInfo->aConstraintUsage; | 2815 pUsage = pIdxInfo->aConstraintUsage; |
| 4877 nConstraint = pIdxInfo->nConstraint; | 2816 nConstraint = pIdxInfo->nConstraint; |
| 4878 if( whereLoopResize(db, pNew, nConstraint) ){ | 2817 if( whereLoopResize(db, pNew, nConstraint) ){ |
| 4879 sqlite3DbFree(db, pIdxInfo); | 2818 sqlite3DbFree(db, pIdxInfo); |
| 4880 return SQLITE_NOMEM; | 2819 return SQLITE_NOMEM; |
| 4881 } | 2820 } |
| 4882 | 2821 |
| 4883 for(iPhase=0; iPhase<=3; iPhase++){ | 2822 for(iPhase=0; iPhase<=3; iPhase++){ |
| 4884 if( !seenIn && (iPhase&1)!=0 ){ | 2823 if( !seenIn && (iPhase&1)!=0 ){ |
| 4885 iPhase++; | 2824 iPhase++; |
| 4886 if( iPhase>3 ) break; | 2825 if( iPhase>3 ) break; |
| 4887 } | 2826 } |
| 4888 if( !seenVar && iPhase>1 ) break; | 2827 if( !seenVar && iPhase>1 ) break; |
| 4889 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; | 2828 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; |
| 4890 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){ | 2829 for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){ |
| 4891 j = pIdxCons->iTermOffset; | 2830 j = pIdxCons->iTermOffset; |
| 4892 pTerm = &pWC->a[j]; | 2831 pTerm = &pWC->a[j]; |
| 4893 switch( iPhase ){ | 2832 switch( iPhase ){ |
| 4894 case 0: /* Constants without IN operator */ | 2833 case 0: /* Constants without IN operator */ |
| 4895 pIdxCons->usable = 0; | 2834 pIdxCons->usable = 0; |
| 4896 if( (pTerm->eOperator & WO_IN)!=0 ){ | 2835 if( (pTerm->eOperator & WO_IN)!=0 ){ |
| 4897 seenIn = 1; | 2836 seenIn = 1; |
| 4898 } | 2837 } |
| 4899 if( pTerm->prereqRight!=0 ){ | 2838 if( (pTerm->prereqRight & ~mExtra)!=0 ){ |
| 4900 seenVar = 1; | 2839 seenVar = 1; |
| 4901 }else if( (pTerm->eOperator & WO_IN)==0 ){ | 2840 }else if( (pTerm->eOperator & WO_IN)==0 ){ |
| 4902 pIdxCons->usable = 1; | 2841 pIdxCons->usable = 1; |
| 4903 } | 2842 } |
| 4904 break; | 2843 break; |
| 4905 case 1: /* Constants with IN operators */ | 2844 case 1: /* Constants with IN operators */ |
| 4906 assert( seenIn ); | 2845 assert( seenIn ); |
| 4907 pIdxCons->usable = (pTerm->prereqRight==0); | 2846 pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0; |
| 4908 break; | 2847 break; |
| 4909 case 2: /* Variables without IN */ | 2848 case 2: /* Variables without IN */ |
| 4910 assert( seenVar ); | 2849 assert( seenVar ); |
| 4911 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0; | 2850 pIdxCons->usable = (pTerm->eOperator & WO_IN)==0; |
| 4912 break; | 2851 break; |
| 4913 default: /* Variables with IN */ | 2852 default: /* Variables with IN */ |
| 4914 assert( seenVar && seenIn ); | 2853 assert( seenVar && seenIn ); |
| 4915 pIdxCons->usable = 1; | 2854 pIdxCons->usable = 1; |
| 4916 break; | 2855 break; |
| 4917 } | 2856 } |
| 4918 } | 2857 } |
| 4919 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint); | 2858 memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint); |
| 4920 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); | 2859 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); |
| 4921 pIdxInfo->idxStr = 0; | 2860 pIdxInfo->idxStr = 0; |
| 4922 pIdxInfo->idxNum = 0; | 2861 pIdxInfo->idxNum = 0; |
| 4923 pIdxInfo->needToFreeIdxStr = 0; | 2862 pIdxInfo->needToFreeIdxStr = 0; |
| 4924 pIdxInfo->orderByConsumed = 0; | 2863 pIdxInfo->orderByConsumed = 0; |
| 4925 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; | 2864 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2; |
| 4926 pIdxInfo->estimatedRows = 25; | 2865 pIdxInfo->estimatedRows = 25; |
| 2866 pIdxInfo->idxFlags = 0; |
| 2867 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed; |
| 4927 rc = vtabBestIndex(pParse, pTab, pIdxInfo); | 2868 rc = vtabBestIndex(pParse, pTab, pIdxInfo); |
| 4928 if( rc ) goto whereLoopAddVtab_exit; | 2869 if( rc ) goto whereLoopAddVtab_exit; |
| 4929 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; | 2870 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint; |
| 4930 pNew->prereq = mExtra; | 2871 pNew->prereq = mExtra; |
| 4931 mxTerm = -1; | 2872 mxTerm = -1; |
| 4932 assert( pNew->nLSlot>=nConstraint ); | 2873 assert( pNew->nLSlot>=nConstraint ); |
| 4933 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0; | 2874 for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0; |
| 4934 pNew->u.vtab.omitMask = 0; | 2875 pNew->u.vtab.omitMask = 0; |
| 4935 for(i=0; i<nConstraint; i++, pIdxCons++){ | 2876 for(i=0; i<nConstraint; i++, pIdxCons++){ |
| 4936 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){ | 2877 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){ |
| (...skipping 25 matching lines...) Expand all Loading... |
| 4962 ** If we do attempt to use such a constraint, some rows might be | 2903 ** If we do attempt to use such a constraint, some rows might be |
| 4963 ** repeated in the output. */ | 2904 ** repeated in the output. */ |
| 4964 break; | 2905 break; |
| 4965 } | 2906 } |
| 4966 /* A virtual table that is constrained by an IN clause may not | 2907 /* A virtual table that is constrained by an IN clause may not |
| 4967 ** consume the ORDER BY clause because (1) the order of IN terms | 2908 ** consume the ORDER BY clause because (1) the order of IN terms |
| 4968 ** is not necessarily related to the order of output terms and | 2909 ** is not necessarily related to the order of output terms and |
| 4969 ** (2) Multiple outputs from a single IN value will not merge | 2910 ** (2) Multiple outputs from a single IN value will not merge |
| 4970 ** together. */ | 2911 ** together. */ |
| 4971 pIdxInfo->orderByConsumed = 0; | 2912 pIdxInfo->orderByConsumed = 0; |
| 2913 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE; |
| 4972 } | 2914 } |
| 4973 } | 2915 } |
| 4974 } | 2916 } |
| 4975 if( i>=nConstraint ){ | 2917 if( i>=nConstraint ){ |
| 4976 pNew->nLTerm = mxTerm+1; | 2918 pNew->nLTerm = mxTerm+1; |
| 4977 assert( pNew->nLTerm<=pNew->nLSlot ); | 2919 assert( pNew->nLTerm<=pNew->nLSlot ); |
| 4978 pNew->u.vtab.idxNum = pIdxInfo->idxNum; | 2920 pNew->u.vtab.idxNum = pIdxInfo->idxNum; |
| 4979 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; | 2921 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr; |
| 4980 pIdxInfo->needToFreeIdxStr = 0; | 2922 pIdxInfo->needToFreeIdxStr = 0; |
| 4981 pNew->u.vtab.idxStr = pIdxInfo->idxStr; | 2923 pNew->u.vtab.idxStr = pIdxInfo->idxStr; |
| 4982 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? | 2924 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ? |
| 4983 pIdxInfo->nOrderBy : 0); | 2925 pIdxInfo->nOrderBy : 0); |
| 4984 pNew->rSetup = 0; | 2926 pNew->rSetup = 0; |
| 4985 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); | 2927 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost); |
| 4986 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); | 2928 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows); |
| 2929 |
| 2930 /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated |
| 2931 ** that the scan will visit at most one row. Clear it otherwise. */ |
| 2932 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){ |
| 2933 pNew->wsFlags |= WHERE_ONEROW; |
| 2934 }else{ |
| 2935 pNew->wsFlags &= ~WHERE_ONEROW; |
| 2936 } |
| 4987 whereLoopInsert(pBuilder, pNew); | 2937 whereLoopInsert(pBuilder, pNew); |
| 4988 if( pNew->u.vtab.needFree ){ | 2938 if( pNew->u.vtab.needFree ){ |
| 4989 sqlite3_free(pNew->u.vtab.idxStr); | 2939 sqlite3_free(pNew->u.vtab.idxStr); |
| 4990 pNew->u.vtab.needFree = 0; | 2940 pNew->u.vtab.needFree = 0; |
| 4991 } | 2941 } |
| 4992 } | 2942 } |
| 4993 } | 2943 } |
| 4994 | 2944 |
| 4995 whereLoopAddVtab_exit: | 2945 whereLoopAddVtab_exit: |
| 4996 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); | 2946 if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr); |
| 4997 sqlite3DbFree(db, pIdxInfo); | 2947 sqlite3DbFree(db, pIdxInfo); |
| 4998 return rc; | 2948 return rc; |
| 4999 } | 2949 } |
| 5000 #endif /* SQLITE_OMIT_VIRTUALTABLE */ | 2950 #endif /* SQLITE_OMIT_VIRTUALTABLE */ |
| 5001 | 2951 |
| 5002 /* | 2952 /* |
| 5003 ** Add WhereLoop entries to handle OR terms. This works for either | 2953 ** Add WhereLoop entries to handle OR terms. This works for either |
| 5004 ** btrees or virtual tables. | 2954 ** btrees or virtual tables. |
| 5005 */ | 2955 */ |
| 5006 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){ | 2956 static int whereLoopAddOr( |
| 2957 WhereLoopBuilder *pBuilder, |
| 2958 Bitmask mExtra, |
| 2959 Bitmask mUnusable |
| 2960 ){ |
| 5007 WhereInfo *pWInfo = pBuilder->pWInfo; | 2961 WhereInfo *pWInfo = pBuilder->pWInfo; |
| 5008 WhereClause *pWC; | 2962 WhereClause *pWC; |
| 5009 WhereLoop *pNew; | 2963 WhereLoop *pNew; |
| 5010 WhereTerm *pTerm, *pWCEnd; | 2964 WhereTerm *pTerm, *pWCEnd; |
| 5011 int rc = SQLITE_OK; | 2965 int rc = SQLITE_OK; |
| 5012 int iCur; | 2966 int iCur; |
| 5013 WhereClause tempWC; | 2967 WhereClause tempWC; |
| 5014 WhereLoopBuilder sSubBuild; | 2968 WhereLoopBuilder sSubBuild; |
| 5015 WhereOrSet sSum, sCur; | 2969 WhereOrSet sSum, sCur; |
| 5016 struct SrcList_item *pItem; | 2970 struct SrcList_item *pItem; |
| (...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 5055 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", | 3009 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", |
| 5056 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); | 3010 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm)); |
| 5057 if( sqlite3WhereTrace & 0x400 ){ | 3011 if( sqlite3WhereTrace & 0x400 ){ |
| 5058 for(i=0; i<sSubBuild.pWC->nTerm; i++){ | 3012 for(i=0; i<sSubBuild.pWC->nTerm; i++){ |
| 5059 whereTermPrint(&sSubBuild.pWC->a[i], i); | 3013 whereTermPrint(&sSubBuild.pWC->a[i], i); |
| 5060 } | 3014 } |
| 5061 } | 3015 } |
| 5062 #endif | 3016 #endif |
| 5063 #ifndef SQLITE_OMIT_VIRTUALTABLE | 3017 #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 5064 if( IsVirtual(pItem->pTab) ){ | 3018 if( IsVirtual(pItem->pTab) ){ |
| 5065 rc = whereLoopAddVirtual(&sSubBuild, mExtra); | 3019 rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable); |
| 5066 }else | 3020 }else |
| 5067 #endif | 3021 #endif |
| 5068 { | 3022 { |
| 5069 rc = whereLoopAddBtree(&sSubBuild, mExtra); | 3023 rc = whereLoopAddBtree(&sSubBuild, mExtra); |
| 5070 } | 3024 } |
| 5071 if( rc==SQLITE_OK ){ | 3025 if( rc==SQLITE_OK ){ |
| 5072 rc = whereLoopAddOr(&sSubBuild, mExtra); | 3026 rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable); |
| 5073 } | 3027 } |
| 5074 assert( rc==SQLITE_OK || sCur.n==0 ); | 3028 assert( rc==SQLITE_OK || sCur.n==0 ); |
| 5075 if( sCur.n==0 ){ | 3029 if( sCur.n==0 ){ |
| 5076 sSum.n = 0; | 3030 sSum.n = 0; |
| 5077 break; | 3031 break; |
| 5078 }else if( once ){ | 3032 }else if( once ){ |
| 5079 whereOrMove(&sSum, &sCur); | 3033 whereOrMove(&sSum, &sCur); |
| 5080 once = 0; | 3034 once = 0; |
| 5081 }else{ | 3035 }else{ |
| 5082 WhereOrSet sPrev; | 3036 WhereOrSet sPrev; |
| (...skipping 41 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 5124 /* | 3078 /* |
| 5125 ** Add all WhereLoop objects for all tables | 3079 ** Add all WhereLoop objects for all tables |
| 5126 */ | 3080 */ |
| 5127 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ | 3081 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){ |
| 5128 WhereInfo *pWInfo = pBuilder->pWInfo; | 3082 WhereInfo *pWInfo = pBuilder->pWInfo; |
| 5129 Bitmask mExtra = 0; | 3083 Bitmask mExtra = 0; |
| 5130 Bitmask mPrior = 0; | 3084 Bitmask mPrior = 0; |
| 5131 int iTab; | 3085 int iTab; |
| 5132 SrcList *pTabList = pWInfo->pTabList; | 3086 SrcList *pTabList = pWInfo->pTabList; |
| 5133 struct SrcList_item *pItem; | 3087 struct SrcList_item *pItem; |
| 3088 struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel]; |
| 5134 sqlite3 *db = pWInfo->pParse->db; | 3089 sqlite3 *db = pWInfo->pParse->db; |
| 5135 int nTabList = pWInfo->nLevel; | |
| 5136 int rc = SQLITE_OK; | 3090 int rc = SQLITE_OK; |
| 5137 u8 priorJoinType = 0; | |
| 5138 WhereLoop *pNew; | 3091 WhereLoop *pNew; |
| 3092 u8 priorJointype = 0; |
| 5139 | 3093 |
| 5140 /* Loop over the tables in the join, from left to right */ | 3094 /* Loop over the tables in the join, from left to right */ |
| 5141 pNew = pBuilder->pNew; | 3095 pNew = pBuilder->pNew; |
| 5142 whereLoopInit(pNew); | 3096 whereLoopInit(pNew); |
| 5143 for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){ | 3097 for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){ |
| 3098 Bitmask mUnusable = 0; |
| 5144 pNew->iTab = iTab; | 3099 pNew->iTab = iTab; |
| 5145 pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor); | 3100 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor); |
| 5146 if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){ | 3101 if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){ |
| 3102 /* This condition is true when pItem is the FROM clause term on the |
| 3103 ** right-hand-side of a LEFT or CROSS JOIN. */ |
| 5147 mExtra = mPrior; | 3104 mExtra = mPrior; |
| 5148 } | 3105 } |
| 5149 priorJoinType = pItem->jointype; | 3106 priorJointype = pItem->fg.jointype; |
| 5150 if( IsVirtual(pItem->pTab) ){ | 3107 if( IsVirtual(pItem->pTab) ){ |
| 5151 rc = whereLoopAddVirtual(pBuilder, mExtra); | 3108 struct SrcList_item *p; |
| 3109 for(p=&pItem[1]; p<pEnd; p++){ |
| 3110 if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){ |
| 3111 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor); |
| 3112 } |
| 3113 } |
| 3114 rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable); |
| 5152 }else{ | 3115 }else{ |
| 5153 rc = whereLoopAddBtree(pBuilder, mExtra); | 3116 rc = whereLoopAddBtree(pBuilder, mExtra); |
| 5154 } | 3117 } |
| 5155 if( rc==SQLITE_OK ){ | 3118 if( rc==SQLITE_OK ){ |
| 5156 rc = whereLoopAddOr(pBuilder, mExtra); | 3119 rc = whereLoopAddOr(pBuilder, mExtra, mUnusable); |
| 5157 } | 3120 } |
| 5158 mPrior |= pNew->maskSelf; | 3121 mPrior |= pNew->maskSelf; |
| 5159 if( rc || db->mallocFailed ) break; | 3122 if( rc || db->mallocFailed ) break; |
| 5160 } | 3123 } |
| 3124 |
| 5161 whereLoopClear(db, pNew); | 3125 whereLoopClear(db, pNew); |
| 5162 return rc; | 3126 return rc; |
| 5163 } | 3127 } |
| 5164 | 3128 |
| 5165 /* | 3129 /* |
| 5166 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th | 3130 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th |
| 5167 ** parameters) to see if it outputs rows in the requested ORDER BY | 3131 ** parameters) to see if it outputs rows in the requested ORDER BY |
| 5168 ** (or GROUP BY) without requiring a separate sort operation. Return N: | 3132 ** (or GROUP BY) without requiring a separate sort operation. Return N: |
| 5169 ** | 3133 ** |
| 5170 ** N>0: N terms of the ORDER BY clause are satisfied | 3134 ** N>0: N terms of the ORDER BY clause are satisfied |
| (...skipping 85 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 5256 /* Mark off any ORDER BY term X that is a column in the table of | 3220 /* Mark off any ORDER BY term X that is a column in the table of |
| 5257 ** the current loop for which there is term in the WHERE | 3221 ** the current loop for which there is term in the WHERE |
| 5258 ** clause of the form X IS NULL or X=? that reference only outer | 3222 ** clause of the form X IS NULL or X=? that reference only outer |
| 5259 ** loops. | 3223 ** loops. |
| 5260 */ | 3224 */ |
| 5261 for(i=0; i<nOrderBy; i++){ | 3225 for(i=0; i<nOrderBy; i++){ |
| 5262 if( MASKBIT(i) & obSat ) continue; | 3226 if( MASKBIT(i) & obSat ) continue; |
| 5263 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); | 3227 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); |
| 5264 if( pOBExpr->op!=TK_COLUMN ) continue; | 3228 if( pOBExpr->op!=TK_COLUMN ) continue; |
| 5265 if( pOBExpr->iTable!=iCur ) continue; | 3229 if( pOBExpr->iTable!=iCur ) continue; |
| 5266 pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, | 3230 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn, |
| 5267 ~ready, WO_EQ|WO_ISNULL, 0); | 3231 ~ready, WO_EQ|WO_ISNULL|WO_IS, 0); |
| 5268 if( pTerm==0 ) continue; | 3232 if( pTerm==0 ) continue; |
| 5269 if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){ | 3233 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){ |
| 5270 const char *z1, *z2; | 3234 const char *z1, *z2; |
| 5271 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); | 3235 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); |
| 5272 if( !pColl ) pColl = db->pDfltColl; | 3236 if( !pColl ) pColl = db->pDfltColl; |
| 5273 z1 = pColl->zName; | 3237 z1 = pColl->zName; |
| 5274 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); | 3238 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr); |
| 5275 if( !pColl ) pColl = db->pDfltColl; | 3239 if( !pColl ) pColl = db->pDfltColl; |
| 5276 z2 = pColl->zName; | 3240 z2 = pColl->zName; |
| 5277 if( sqlite3StrICmp(z1, z2)!=0 ) continue; | 3241 if( sqlite3StrICmp(z1, z2)!=0 ) continue; |
| 3242 testcase( pTerm->pExpr->op==TK_IS ); |
| 5278 } | 3243 } |
| 5279 obSat |= MASKBIT(i); | 3244 obSat |= MASKBIT(i); |
| 5280 } | 3245 } |
| 5281 | 3246 |
| 5282 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ | 3247 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){ |
| 5283 if( pLoop->wsFlags & WHERE_IPK ){ | 3248 if( pLoop->wsFlags & WHERE_IPK ){ |
| 5284 pIndex = 0; | 3249 pIndex = 0; |
| 5285 nKeyCol = 0; | 3250 nKeyCol = 0; |
| 5286 nColumn = 1; | 3251 nColumn = 1; |
| 5287 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ | 3252 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){ |
| 5288 return 0; | 3253 return 0; |
| 5289 }else{ | 3254 }else{ |
| 5290 nKeyCol = pIndex->nKeyCol; | 3255 nKeyCol = pIndex->nKeyCol; |
| 5291 nColumn = pIndex->nColumn; | 3256 nColumn = pIndex->nColumn; |
| 5292 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); | 3257 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) ); |
| 5293 assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable)); | 3258 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID |
| 3259 || !HasRowid(pIndex->pTable)); |
| 5294 isOrderDistinct = IsUniqueIndex(pIndex); | 3260 isOrderDistinct = IsUniqueIndex(pIndex); |
| 5295 } | 3261 } |
| 5296 | 3262 |
| 5297 /* Loop through all columns of the index and deal with the ones | 3263 /* Loop through all columns of the index and deal with the ones |
| 5298 ** that are not constrained by == or IN. | 3264 ** that are not constrained by == or IN. |
| 5299 */ | 3265 */ |
| 5300 rev = revSet = 0; | 3266 rev = revSet = 0; |
| 5301 distinctColumns = 0; | 3267 distinctColumns = 0; |
| 5302 for(j=0; j<nColumn; j++){ | 3268 for(j=0; j<nColumn; j++){ |
| 5303 u8 bOnce; /* True to run the ORDER BY search loop */ | 3269 u8 bOnce; /* True to run the ORDER BY search loop */ |
| 5304 | 3270 |
| 5305 /* Skip over == and IS NULL terms */ | 3271 /* Skip over == and IS NULL terms */ |
| 5306 if( j<pLoop->u.btree.nEq | 3272 if( j<pLoop->u.btree.nEq |
| 5307 && pLoop->u.btree.nSkip==0 | 3273 && pLoop->nSkip==0 |
| 5308 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0 | 3274 && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0 |
| 5309 ){ | 3275 ){ |
| 5310 if( i & WO_ISNULL ){ | 3276 if( i & WO_ISNULL ){ |
| 5311 testcase( isOrderDistinct ); | 3277 testcase( isOrderDistinct ); |
| 5312 isOrderDistinct = 0; | 3278 isOrderDistinct = 0; |
| 5313 } | 3279 } |
| 5314 continue; | 3280 continue; |
| 5315 } | 3281 } |
| 5316 | 3282 |
| 5317 /* Get the column number in the table (iColumn) and sort order | 3283 /* Get the column number in the table (iColumn) and sort order |
| 5318 ** (revIdx) for the j-th column of the index. | 3284 ** (revIdx) for the j-th column of the index. |
| 5319 */ | 3285 */ |
| 5320 if( pIndex ){ | 3286 if( pIndex ){ |
| 5321 iColumn = pIndex->aiColumn[j]; | 3287 iColumn = pIndex->aiColumn[j]; |
| 5322 revIdx = pIndex->aSortOrder[j]; | 3288 revIdx = pIndex->aSortOrder[j]; |
| 5323 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; | 3289 if( iColumn==pIndex->pTable->iPKey ) iColumn = -1; |
| 5324 }else{ | 3290 }else{ |
| 5325 iColumn = -1; | 3291 iColumn = XN_ROWID; |
| 5326 revIdx = 0; | 3292 revIdx = 0; |
| 5327 } | 3293 } |
| 5328 | 3294 |
| 5329 /* An unconstrained column that might be NULL means that this | 3295 /* An unconstrained column that might be NULL means that this |
| 5330 ** WhereLoop is not well-ordered | 3296 ** WhereLoop is not well-ordered |
| 5331 */ | 3297 */ |
| 5332 if( isOrderDistinct | 3298 if( isOrderDistinct |
| 5333 && iColumn>=0 | 3299 && iColumn>=0 |
| 5334 && j>=pLoop->u.btree.nEq | 3300 && j>=pLoop->u.btree.nEq |
| 5335 && pIndex->pTable->aCol[iColumn].notNull==0 | 3301 && pIndex->pTable->aCol[iColumn].notNull==0 |
| 5336 ){ | 3302 ){ |
| 5337 isOrderDistinct = 0; | 3303 isOrderDistinct = 0; |
| 5338 } | 3304 } |
| 5339 | 3305 |
| 5340 /* Find the ORDER BY term that corresponds to the j-th column | 3306 /* Find the ORDER BY term that corresponds to the j-th column |
| 5341 ** of the index and mark that ORDER BY term off | 3307 ** of the index and mark that ORDER BY term off |
| 5342 */ | 3308 */ |
| 5343 bOnce = 1; | 3309 bOnce = 1; |
| 5344 isMatch = 0; | 3310 isMatch = 0; |
| 5345 for(i=0; bOnce && i<nOrderBy; i++){ | 3311 for(i=0; bOnce && i<nOrderBy; i++){ |
| 5346 if( MASKBIT(i) & obSat ) continue; | 3312 if( MASKBIT(i) & obSat ) continue; |
| 5347 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); | 3313 pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr); |
| 5348 testcase( wctrlFlags & WHERE_GROUPBY ); | 3314 testcase( wctrlFlags & WHERE_GROUPBY ); |
| 5349 testcase( wctrlFlags & WHERE_DISTINCTBY ); | 3315 testcase( wctrlFlags & WHERE_DISTINCTBY ); |
| 5350 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; | 3316 if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0; |
| 5351 if( pOBExpr->op!=TK_COLUMN ) continue; | 3317 if( iColumn>=(-1) ){ |
| 5352 if( pOBExpr->iTable!=iCur ) continue; | 3318 if( pOBExpr->op!=TK_COLUMN ) continue; |
| 5353 if( pOBExpr->iColumn!=iColumn ) continue; | 3319 if( pOBExpr->iTable!=iCur ) continue; |
| 3320 if( pOBExpr->iColumn!=iColumn ) continue; |
| 3321 }else{ |
| 3322 if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){ |
| 3323 continue; |
| 3324 } |
| 3325 } |
| 5354 if( iColumn>=0 ){ | 3326 if( iColumn>=0 ){ |
| 5355 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); | 3327 pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr); |
| 5356 if( !pColl ) pColl = db->pDfltColl; | 3328 if( !pColl ) pColl = db->pDfltColl; |
| 5357 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; | 3329 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue; |
| 5358 } | 3330 } |
| 5359 isMatch = 1; | 3331 isMatch = 1; |
| 5360 break; | 3332 break; |
| 5361 } | 3333 } |
| 5362 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){ | 3334 if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){ |
| 5363 /* Make sure the sort order is compatible in an ORDER BY clause. | 3335 /* Make sure the sort order is compatible in an ORDER BY clause. |
| (...skipping 28 matching lines...) Expand all Loading... |
| 5392 } /* end-if not one-row */ | 3364 } /* end-if not one-row */ |
| 5393 | 3365 |
| 5394 /* Mark off any other ORDER BY terms that reference pLoop */ | 3366 /* Mark off any other ORDER BY terms that reference pLoop */ |
| 5395 if( isOrderDistinct ){ | 3367 if( isOrderDistinct ){ |
| 5396 orderDistinctMask |= pLoop->maskSelf; | 3368 orderDistinctMask |= pLoop->maskSelf; |
| 5397 for(i=0; i<nOrderBy; i++){ | 3369 for(i=0; i<nOrderBy; i++){ |
| 5398 Expr *p; | 3370 Expr *p; |
| 5399 Bitmask mTerm; | 3371 Bitmask mTerm; |
| 5400 if( MASKBIT(i) & obSat ) continue; | 3372 if( MASKBIT(i) & obSat ) continue; |
| 5401 p = pOrderBy->a[i].pExpr; | 3373 p = pOrderBy->a[i].pExpr; |
| 5402 mTerm = exprTableUsage(&pWInfo->sMaskSet,p); | 3374 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p); |
| 5403 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; | 3375 if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue; |
| 5404 if( (mTerm&~orderDistinctMask)==0 ){ | 3376 if( (mTerm&~orderDistinctMask)==0 ){ |
| 5405 obSat |= MASKBIT(i); | 3377 obSat |= MASKBIT(i); |
| 5406 } | 3378 } |
| 5407 } | 3379 } |
| 5408 } | 3380 } |
| 5409 } /* End the loop over all WhereLoops from outer-most down to inner-most */ | 3381 } /* End the loop over all WhereLoops from outer-most down to inner-most */ |
| 5410 if( obSat==obDone ) return (i8)nOrderBy; | 3382 if( obSat==obDone ) return (i8)nOrderBy; |
| 5411 if( !isOrderDistinct ){ | 3383 if( !isOrderDistinct ){ |
| 5412 for(i=nOrderBy-1; i>0; i--){ | 3384 for(i=nOrderBy-1; i>0; i--){ |
| (...skipping 161 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 5574 ** the ORDER BY clause are already in order, where X is the array | 3546 ** the ORDER BY clause are already in order, where X is the array |
| 5575 ** index. */ | 3547 ** index. */ |
| 5576 aSortCost = (LogEst*)pX; | 3548 aSortCost = (LogEst*)pX; |
| 5577 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy); | 3549 memset(aSortCost, 0, sizeof(LogEst) * nOrderBy); |
| 5578 } | 3550 } |
| 5579 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] ); | 3551 assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] ); |
| 5580 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX ); | 3552 assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX ); |
| 5581 | 3553 |
| 5582 /* Seed the search with a single WherePath containing zero WhereLoops. | 3554 /* Seed the search with a single WherePath containing zero WhereLoops. |
| 5583 ** | 3555 ** |
| 5584 ** TUNING: Do not let the number of iterations go above 25. If the cost | 3556 ** TUNING: Do not let the number of iterations go above 28. If the cost |
| 5585 ** of computing an automatic index is not paid back within the first 25 | 3557 ** of computing an automatic index is not paid back within the first 28 |
| 5586 ** rows, then do not use the automatic index. */ | 3558 ** rows, then do not use the automatic index. */ |
| 5587 aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) ); | 3559 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) ); |
| 5588 nFrom = 1; | 3560 nFrom = 1; |
| 5589 assert( aFrom[0].isOrdered==0 ); | 3561 assert( aFrom[0].isOrdered==0 ); |
| 5590 if( nOrderBy ){ | 3562 if( nOrderBy ){ |
| 5591 /* If nLoop is zero, then there are no FROM terms in the query. Since | 3563 /* If nLoop is zero, then there are no FROM terms in the query. Since |
| 5592 ** in this case the query may return a maximum of one row, the results | 3564 ** in this case the query may return a maximum of one row, the results |
| 5593 ** are already in the requested order. Set isOrdered to nOrderBy to | 3565 ** are already in the requested order. Set isOrdered to nOrderBy to |
| 5594 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to | 3566 ** indicate this. Or, if nLoop is greater than zero, set isOrdered to |
| 5595 ** -1, indicating that the result set may or may not be ordered, | 3567 ** -1, indicating that the result set may or may not be ordered, |
| 5596 ** depending on the loops added to the current plan. */ | 3568 ** depending on the loops added to the current plan. */ |
| 5597 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy; | 3569 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy; |
| (...skipping 153 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 5751 mxCost = pTo->rCost; | 3723 mxCost = pTo->rCost; |
| 5752 mxUnsorted = pTo->rUnsorted; | 3724 mxUnsorted = pTo->rUnsorted; |
| 5753 mxI = jj; | 3725 mxI = jj; |
| 5754 } | 3726 } |
| 5755 } | 3727 } |
| 5756 } | 3728 } |
| 5757 } | 3729 } |
| 5758 } | 3730 } |
| 5759 | 3731 |
| 5760 #ifdef WHERETRACE_ENABLED /* >=2 */ | 3732 #ifdef WHERETRACE_ENABLED /* >=2 */ |
| 5761 if( sqlite3WhereTrace>=2 ){ | 3733 if( sqlite3WhereTrace & 0x02 ){ |
| 5762 sqlite3DebugPrintf("---- after round %d ----\n", iLoop); | 3734 sqlite3DebugPrintf("---- after round %d ----\n", iLoop); |
| 5763 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){ | 3735 for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){ |
| 5764 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c", | 3736 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c", |
| 5765 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, | 3737 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow, |
| 5766 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); | 3738 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?'); |
| 5767 if( pTo->isOrdered>0 ){ | 3739 if( pTo->isOrdered>0 ){ |
| 5768 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); | 3740 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop); |
| 5769 }else{ | 3741 }else{ |
| 5770 sqlite3DebugPrintf("\n"); | 3742 sqlite3DebugPrintf("\n"); |
| 5771 } | 3743 } |
| (...skipping 43 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 5815 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ | 3787 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){ |
| 5816 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ | 3788 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){ |
| 5817 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; | 3789 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED; |
| 5818 } | 3790 } |
| 5819 }else{ | 3791 }else{ |
| 5820 pWInfo->nOBSat = pFrom->isOrdered; | 3792 pWInfo->nOBSat = pFrom->isOrdered; |
| 5821 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0; | 3793 if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0; |
| 5822 pWInfo->revMask = pFrom->revLoop; | 3794 pWInfo->revMask = pFrom->revLoop; |
| 5823 } | 3795 } |
| 5824 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) | 3796 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP) |
| 5825 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr | 3797 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0 |
| 5826 ){ | 3798 ){ |
| 5827 Bitmask revMask = 0; | 3799 Bitmask revMask = 0; |
| 5828 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, | 3800 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, |
| 5829 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask | 3801 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask |
| 5830 ); | 3802 ); |
| 5831 assert( pWInfo->sorted==0 ); | 3803 assert( pWInfo->sorted==0 ); |
| 5832 if( nOrder==pWInfo->pOrderBy->nExpr ){ | 3804 if( nOrder==pWInfo->pOrderBy->nExpr ){ |
| 5833 pWInfo->sorted = 1; | 3805 pWInfo->sorted = 1; |
| 5834 pWInfo->revMask = revMask; | 3806 pWInfo->revMask = revMask; |
| 5835 } | 3807 } |
| (...skipping 29 matching lines...) Expand all Loading... |
| 5865 int j; | 3837 int j; |
| 5866 Table *pTab; | 3838 Table *pTab; |
| 5867 Index *pIdx; | 3839 Index *pIdx; |
| 5868 | 3840 |
| 5869 pWInfo = pBuilder->pWInfo; | 3841 pWInfo = pBuilder->pWInfo; |
| 5870 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0; | 3842 if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0; |
| 5871 assert( pWInfo->pTabList->nSrc>=1 ); | 3843 assert( pWInfo->pTabList->nSrc>=1 ); |
| 5872 pItem = pWInfo->pTabList->a; | 3844 pItem = pWInfo->pTabList->a; |
| 5873 pTab = pItem->pTab; | 3845 pTab = pItem->pTab; |
| 5874 if( IsVirtual(pTab) ) return 0; | 3846 if( IsVirtual(pTab) ) return 0; |
| 5875 if( pItem->zIndex ) return 0; | 3847 if( pItem->fg.isIndexedBy ) return 0; |
| 5876 iCur = pItem->iCursor; | 3848 iCur = pItem->iCursor; |
| 5877 pWC = &pWInfo->sWC; | 3849 pWC = &pWInfo->sWC; |
| 5878 pLoop = pBuilder->pNew; | 3850 pLoop = pBuilder->pNew; |
| 5879 pLoop->wsFlags = 0; | 3851 pLoop->wsFlags = 0; |
| 5880 pLoop->u.btree.nSkip = 0; | 3852 pLoop->nSkip = 0; |
| 5881 pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0); | 3853 pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0); |
| 5882 if( pTerm ){ | 3854 if( pTerm ){ |
| 3855 testcase( pTerm->eOperator & WO_IS ); |
| 5883 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; | 3856 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW; |
| 5884 pLoop->aLTerm[0] = pTerm; | 3857 pLoop->aLTerm[0] = pTerm; |
| 5885 pLoop->nLTerm = 1; | 3858 pLoop->nLTerm = 1; |
| 5886 pLoop->u.btree.nEq = 1; | 3859 pLoop->u.btree.nEq = 1; |
| 5887 /* TUNING: Cost of a rowid lookup is 10 */ | 3860 /* TUNING: Cost of a rowid lookup is 10 */ |
| 5888 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ | 3861 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */ |
| 5889 }else{ | 3862 }else{ |
| 5890 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ | 3863 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ |
| 3864 int opMask; |
| 5891 assert( pLoop->aLTermSpace==pLoop->aLTerm ); | 3865 assert( pLoop->aLTermSpace==pLoop->aLTerm ); |
| 5892 assert( ArraySize(pLoop->aLTermSpace)==4 ); | |
| 5893 if( !IsUniqueIndex(pIdx) | 3866 if( !IsUniqueIndex(pIdx) |
| 5894 || pIdx->pPartIdxWhere!=0 | 3867 || pIdx->pPartIdxWhere!=0 |
| 5895 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) | 3868 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) |
| 5896 ) continue; | 3869 ) continue; |
| 3870 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ; |
| 5897 for(j=0; j<pIdx->nKeyCol; j++){ | 3871 for(j=0; j<pIdx->nKeyCol; j++){ |
| 5898 pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx); | 3872 pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx); |
| 5899 if( pTerm==0 ) break; | 3873 if( pTerm==0 ) break; |
| 3874 testcase( pTerm->eOperator & WO_IS ); |
| 5900 pLoop->aLTerm[j] = pTerm; | 3875 pLoop->aLTerm[j] = pTerm; |
| 5901 } | 3876 } |
| 5902 if( j!=pIdx->nKeyCol ) continue; | 3877 if( j!=pIdx->nKeyCol ) continue; |
| 5903 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; | 3878 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED; |
| 5904 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ | 3879 if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){ |
| 5905 pLoop->wsFlags |= WHERE_IDX_ONLY; | 3880 pLoop->wsFlags |= WHERE_IDX_ONLY; |
| 5906 } | 3881 } |
| 5907 pLoop->nLTerm = j; | 3882 pLoop->nLTerm = j; |
| 5908 pLoop->u.btree.nEq = j; | 3883 pLoop->u.btree.nEq = j; |
| 5909 pLoop->u.btree.pIndex = pIdx; | 3884 pLoop->u.btree.pIndex = pIdx; |
| 5910 /* TUNING: Cost of a unique index lookup is 15 */ | 3885 /* TUNING: Cost of a unique index lookup is 15 */ |
| 5911 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ | 3886 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */ |
| 5912 break; | 3887 break; |
| 5913 } | 3888 } |
| 5914 } | 3889 } |
| 5915 if( pLoop->wsFlags ){ | 3890 if( pLoop->wsFlags ){ |
| 5916 pLoop->nOut = (LogEst)1; | 3891 pLoop->nOut = (LogEst)1; |
| 5917 pWInfo->a[0].pWLoop = pLoop; | 3892 pWInfo->a[0].pWLoop = pLoop; |
| 5918 pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur); | 3893 pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); |
| 5919 pWInfo->a[0].iTabCur = iCur; | 3894 pWInfo->a[0].iTabCur = iCur; |
| 5920 pWInfo->nRowOut = 1; | 3895 pWInfo->nRowOut = 1; |
| 5921 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; | 3896 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr; |
| 5922 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ | 3897 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){ |
| 5923 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; | 3898 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; |
| 5924 } | 3899 } |
| 5925 #ifdef SQLITE_DEBUG | 3900 #ifdef SQLITE_DEBUG |
| 5926 pLoop->cId = '0'; | 3901 pLoop->cId = '0'; |
| 5927 #endif | 3902 #endif |
| 5928 return 1; | 3903 return 1; |
| (...skipping 103 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 6032 WhereInfo *pWInfo; /* Will become the return value of this function */ | 4007 WhereInfo *pWInfo; /* Will become the return value of this function */ |
| 6033 Vdbe *v = pParse->pVdbe; /* The virtual database engine */ | 4008 Vdbe *v = pParse->pVdbe; /* The virtual database engine */ |
| 6034 Bitmask notReady; /* Cursors that are not yet positioned */ | 4009 Bitmask notReady; /* Cursors that are not yet positioned */ |
| 6035 WhereLoopBuilder sWLB; /* The WhereLoop builder */ | 4010 WhereLoopBuilder sWLB; /* The WhereLoop builder */ |
| 6036 WhereMaskSet *pMaskSet; /* The expression mask set */ | 4011 WhereMaskSet *pMaskSet; /* The expression mask set */ |
| 6037 WhereLevel *pLevel; /* A single level in pWInfo->a[] */ | 4012 WhereLevel *pLevel; /* A single level in pWInfo->a[] */ |
| 6038 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ | 4013 WhereLoop *pLoop; /* Pointer to a single WhereLoop object */ |
| 6039 int ii; /* Loop counter */ | 4014 int ii; /* Loop counter */ |
| 6040 sqlite3 *db; /* Database connection */ | 4015 sqlite3 *db; /* Database connection */ |
| 6041 int rc; /* Return code */ | 4016 int rc; /* Return code */ |
| 4017 u8 bFordelete = 0; |
| 6042 | 4018 |
| 4019 assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || ( |
| 4020 (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 |
| 4021 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 |
| 4022 )); |
| 6043 | 4023 |
| 6044 /* Variable initialization */ | 4024 /* Variable initialization */ |
| 6045 db = pParse->db; | 4025 db = pParse->db; |
| 6046 memset(&sWLB, 0, sizeof(sWLB)); | 4026 memset(&sWLB, 0, sizeof(sWLB)); |
| 6047 | 4027 |
| 6048 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ | 4028 /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */ |
| 6049 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); | 4029 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 ); |
| 6050 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0; | 4030 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0; |
| 6051 sWLB.pOrderBy = pOrderBy; | 4031 sWLB.pOrderBy = pOrderBy; |
| 6052 | 4032 |
| (...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 6088 } | 4068 } |
| 6089 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; | 4069 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1; |
| 6090 pWInfo->nLevel = nTabList; | 4070 pWInfo->nLevel = nTabList; |
| 6091 pWInfo->pParse = pParse; | 4071 pWInfo->pParse = pParse; |
| 6092 pWInfo->pTabList = pTabList; | 4072 pWInfo->pTabList = pTabList; |
| 6093 pWInfo->pOrderBy = pOrderBy; | 4073 pWInfo->pOrderBy = pOrderBy; |
| 6094 pWInfo->pResultSet = pResultSet; | 4074 pWInfo->pResultSet = pResultSet; |
| 6095 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v); | 4075 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v); |
| 6096 pWInfo->wctrlFlags = wctrlFlags; | 4076 pWInfo->wctrlFlags = wctrlFlags; |
| 6097 pWInfo->savedNQueryLoop = pParse->nQueryLoop; | 4077 pWInfo->savedNQueryLoop = pParse->nQueryLoop; |
| 4078 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */ |
| 6098 pMaskSet = &pWInfo->sMaskSet; | 4079 pMaskSet = &pWInfo->sMaskSet; |
| 6099 sWLB.pWInfo = pWInfo; | 4080 sWLB.pWInfo = pWInfo; |
| 6100 sWLB.pWC = &pWInfo->sWC; | 4081 sWLB.pWC = &pWInfo->sWC; |
| 6101 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); | 4082 sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo); |
| 6102 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); | 4083 assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) ); |
| 6103 whereLoopInit(sWLB.pNew); | 4084 whereLoopInit(sWLB.pNew); |
| 6104 #ifdef SQLITE_DEBUG | 4085 #ifdef SQLITE_DEBUG |
| 6105 sWLB.pNew->cId = '*'; | 4086 sWLB.pNew->cId = '*'; |
| 6106 #endif | 4087 #endif |
| 6107 | 4088 |
| 6108 /* Split the WHERE clause into separate subexpressions where each | 4089 /* Split the WHERE clause into separate subexpressions where each |
| 6109 ** subexpression is separated by an AND operator. | 4090 ** subexpression is separated by an AND operator. |
| 6110 */ | 4091 */ |
| 6111 initMaskSet(pMaskSet); | 4092 initMaskSet(pMaskSet); |
| 6112 whereClauseInit(&pWInfo->sWC, pWInfo); | 4093 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo); |
| 6113 whereSplit(&pWInfo->sWC, pWhere, TK_AND); | 4094 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND); |
| 6114 | 4095 |
| 6115 /* Special case: a WHERE clause that is constant. Evaluate the | 4096 /* Special case: a WHERE clause that is constant. Evaluate the |
| 6116 ** expression and either jump over all of the code or fall thru. | 4097 ** expression and either jump over all of the code or fall thru. |
| 6117 */ | 4098 */ |
| 6118 for(ii=0; ii<sWLB.pWC->nTerm; ii++){ | 4099 for(ii=0; ii<sWLB.pWC->nTerm; ii++){ |
| 6119 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){ | 4100 if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){ |
| 6120 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak, | 4101 sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak, |
| 6121 SQLITE_JUMPIFNULL); | 4102 SQLITE_JUMPIFNULL); |
| 6122 sWLB.pWC->a[ii].wtFlags |= TERM_CODED; | 4103 sWLB.pWC->a[ii].wtFlags |= TERM_CODED; |
| 6123 } | 4104 } |
| 6124 } | 4105 } |
| 6125 | 4106 |
| 6126 /* Special case: No FROM clause | 4107 /* Special case: No FROM clause |
| 6127 */ | 4108 */ |
| 6128 if( nTabList==0 ){ | 4109 if( nTabList==0 ){ |
| 6129 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; | 4110 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr; |
| 6130 if( wctrlFlags & WHERE_WANT_DISTINCT ){ | 4111 if( wctrlFlags & WHERE_WANT_DISTINCT ){ |
| 6131 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; | 4112 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; |
| 6132 } | 4113 } |
| 6133 } | 4114 } |
| 6134 | 4115 |
| 6135 /* Assign a bit from the bitmask to every term in the FROM clause. | 4116 /* Assign a bit from the bitmask to every term in the FROM clause. |
| 6136 ** | 4117 ** |
| 6137 ** When assigning bitmask values to FROM clause cursors, it must be | 4118 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N. |
| 6138 ** the case that if X is the bitmask for the N-th FROM clause term then | 4119 ** |
| 6139 ** the bitmask for all FROM clause terms to the left of the N-th term | 4120 ** The rule of the previous sentence ensures thta if X is the bitmask for |
| 6140 ** is (X-1). An expression from the ON clause of a LEFT JOIN can use | 4121 ** a table T, then X-1 is the bitmask for all other tables to the left of T. |
| 6141 ** its Expr.iRightJoinTable value to find the bitmask of the right table | 4122 ** Knowing the bitmask for all tables to the left of a left join is |
| 6142 ** of the join. Subtracting one from the right table bitmask gives a | 4123 ** important. Ticket #3015. |
| 6143 ** bitmask for all tables to the left of the join. Knowing the bitmask | |
| 6144 ** for all tables to the left of a left join is important. Ticket #3015. | |
| 6145 ** | 4124 ** |
| 6146 ** Note that bitmasks are created for all pTabList->nSrc tables in | 4125 ** Note that bitmasks are created for all pTabList->nSrc tables in |
| 6147 ** pTabList, not just the first nTabList tables. nTabList is normally | 4126 ** pTabList, not just the first nTabList tables. nTabList is normally |
| 6148 ** equal to pTabList->nSrc but might be shortened to 1 if the | 4127 ** equal to pTabList->nSrc but might be shortened to 1 if the |
| 6149 ** WHERE_ONETABLE_ONLY flag is set. | 4128 ** WHERE_ONETABLE_ONLY flag is set. |
| 6150 */ | 4129 */ |
| 6151 for(ii=0; ii<pTabList->nSrc; ii++){ | 4130 for(ii=0; ii<pTabList->nSrc; ii++){ |
| 6152 createMask(pMaskSet, pTabList->a[ii].iCursor); | 4131 createMask(pMaskSet, pTabList->a[ii].iCursor); |
| 4132 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC); |
| 6153 } | 4133 } |
| 6154 #ifndef NDEBUG | 4134 #ifdef SQLITE_DEBUG |
| 6155 { | 4135 for(ii=0; ii<pTabList->nSrc; ii++){ |
| 6156 Bitmask toTheLeft = 0; | 4136 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor); |
| 6157 for(ii=0; ii<pTabList->nSrc; ii++){ | 4137 assert( m==MASKBIT(ii) ); |
| 6158 Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor); | |
| 6159 assert( (m-1)==toTheLeft ); | |
| 6160 toTheLeft |= m; | |
| 6161 } | |
| 6162 } | 4138 } |
| 6163 #endif | 4139 #endif |
| 6164 | 4140 |
| 6165 /* Analyze all of the subexpressions. Note that exprAnalyze() might | 4141 /* Analyze all of the subexpressions. */ |
| 6166 ** add new virtual terms onto the end of the WHERE clause. We do not | 4142 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC); |
| 6167 ** want to analyze these virtual terms, so start analyzing at the end | 4143 if( db->mallocFailed ) goto whereBeginError; |
| 6168 ** and work forward so that the added virtual terms are never processed. | |
| 6169 */ | |
| 6170 exprAnalyzeAll(pTabList, &pWInfo->sWC); | |
| 6171 if( db->mallocFailed ){ | |
| 6172 goto whereBeginError; | |
| 6173 } | |
| 6174 | 4144 |
| 6175 if( wctrlFlags & WHERE_WANT_DISTINCT ){ | 4145 if( wctrlFlags & WHERE_WANT_DISTINCT ){ |
| 6176 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ | 4146 if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){ |
| 6177 /* The DISTINCT marking is pointless. Ignore it. */ | 4147 /* The DISTINCT marking is pointless. Ignore it. */ |
| 6178 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; | 4148 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE; |
| 6179 }else if( pOrderBy==0 ){ | 4149 }else if( pOrderBy==0 ){ |
| 6180 /* Try to ORDER BY the result set to make distinct processing easier */ | 4150 /* Try to ORDER BY the result set to make distinct processing easier */ |
| 6181 pWInfo->wctrlFlags |= WHERE_DISTINCTBY; | 4151 pWInfo->wctrlFlags |= WHERE_DISTINCTBY; |
| 6182 pWInfo->pOrderBy = pResultSet; | 4152 pWInfo->pOrderBy = pResultSet; |
| 6183 } | 4153 } |
| 6184 } | 4154 } |
| 6185 | 4155 |
| 6186 /* Construct the WhereLoop objects */ | 4156 /* Construct the WhereLoop objects */ |
| 6187 WHERETRACE(0xffff,("*** Optimizer Start ***\n")); | 4157 WHERETRACE(0xffff,("*** Optimizer Start *** (wctrlFlags: 0x%x)\n", |
| 4158 wctrlFlags)); |
| 6188 #if defined(WHERETRACE_ENABLED) | 4159 #if defined(WHERETRACE_ENABLED) |
| 6189 /* Display all terms of the WHERE clause */ | 4160 if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */ |
| 6190 if( sqlite3WhereTrace & 0x100 ){ | |
| 6191 int i; | 4161 int i; |
| 6192 for(i=0; i<sWLB.pWC->nTerm; i++){ | 4162 for(i=0; i<sWLB.pWC->nTerm; i++){ |
| 6193 whereTermPrint(&sWLB.pWC->a[i], i); | 4163 whereTermPrint(&sWLB.pWC->a[i], i); |
| 6194 } | 4164 } |
| 6195 } | 4165 } |
| 6196 #endif | 4166 #endif |
| 6197 | 4167 |
| 6198 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ | 4168 if( nTabList!=1 || whereShortCut(&sWLB)==0 ){ |
| 6199 rc = whereLoopAddAll(&sWLB); | 4169 rc = whereLoopAddAll(&sWLB); |
| 6200 if( rc ) goto whereBeginError; | 4170 if( rc ) goto whereBeginError; |
| 6201 | 4171 |
| 6202 /* Display all of the WhereLoop objects if wheretrace is enabled */ | 4172 #ifdef WHERETRACE_ENABLED |
| 6203 #ifdef WHERETRACE_ENABLED /* !=0 */ | 4173 if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */ |
| 6204 if( sqlite3WhereTrace ){ | |
| 6205 WhereLoop *p; | 4174 WhereLoop *p; |
| 6206 int i; | 4175 int i; |
| 6207 static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" | 4176 static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz" |
| 6208 "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; | 4177 "ABCDEFGHIJKLMNOPQRSTUVWYXZ"; |
| 6209 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ | 4178 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){ |
| 6210 p->cId = zLabel[i%sizeof(zLabel)]; | 4179 p->cId = zLabel[i%sizeof(zLabel)]; |
| 6211 whereLoopPrint(p, sWLB.pWC); | 4180 whereLoopPrint(p, sWLB.pWC); |
| 6212 } | 4181 } |
| 6213 } | 4182 } |
| 6214 #endif | 4183 #endif |
| 6215 | 4184 |
| 6216 wherePathSolver(pWInfo, 0); | 4185 wherePathSolver(pWInfo, 0); |
| 6217 if( db->mallocFailed ) goto whereBeginError; | 4186 if( db->mallocFailed ) goto whereBeginError; |
| 6218 if( pWInfo->pOrderBy ){ | 4187 if( pWInfo->pOrderBy ){ |
| 6219 wherePathSolver(pWInfo, pWInfo->nRowOut+1); | 4188 wherePathSolver(pWInfo, pWInfo->nRowOut+1); |
| 6220 if( db->mallocFailed ) goto whereBeginError; | 4189 if( db->mallocFailed ) goto whereBeginError; |
| 6221 } | 4190 } |
| 6222 } | 4191 } |
| 6223 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ | 4192 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){ |
| 6224 pWInfo->revMask = (Bitmask)(-1); | 4193 pWInfo->revMask = (Bitmask)(-1); |
| 6225 } | 4194 } |
| 6226 if( pParse->nErr || NEVER(db->mallocFailed) ){ | 4195 if( pParse->nErr || NEVER(db->mallocFailed) ){ |
| 6227 goto whereBeginError; | 4196 goto whereBeginError; |
| 6228 } | 4197 } |
| 6229 #ifdef WHERETRACE_ENABLED /* !=0 */ | 4198 #ifdef WHERETRACE_ENABLED |
| 6230 if( sqlite3WhereTrace ){ | 4199 if( sqlite3WhereTrace ){ |
| 6231 int ii; | |
| 6232 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); | 4200 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut); |
| 6233 if( pWInfo->nOBSat>0 ){ | 4201 if( pWInfo->nOBSat>0 ){ |
| 6234 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); | 4202 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask); |
| 6235 } | 4203 } |
| 6236 switch( pWInfo->eDistinct ){ | 4204 switch( pWInfo->eDistinct ){ |
| 6237 case WHERE_DISTINCT_UNIQUE: { | 4205 case WHERE_DISTINCT_UNIQUE: { |
| 6238 sqlite3DebugPrintf(" DISTINCT=unique"); | 4206 sqlite3DebugPrintf(" DISTINCT=unique"); |
| 6239 break; | 4207 break; |
| 6240 } | 4208 } |
| 6241 case WHERE_DISTINCT_ORDERED: { | 4209 case WHERE_DISTINCT_ORDERED: { |
| 6242 sqlite3DebugPrintf(" DISTINCT=ordered"); | 4210 sqlite3DebugPrintf(" DISTINCT=ordered"); |
| 6243 break; | 4211 break; |
| 6244 } | 4212 } |
| 6245 case WHERE_DISTINCT_UNORDERED: { | 4213 case WHERE_DISTINCT_UNORDERED: { |
| 6246 sqlite3DebugPrintf(" DISTINCT=unordered"); | 4214 sqlite3DebugPrintf(" DISTINCT=unordered"); |
| 6247 break; | 4215 break; |
| 6248 } | 4216 } |
| 6249 } | 4217 } |
| 6250 sqlite3DebugPrintf("\n"); | 4218 sqlite3DebugPrintf("\n"); |
| 6251 for(ii=0; ii<pWInfo->nLevel; ii++){ | 4219 for(ii=0; ii<pWInfo->nLevel; ii++){ |
| 6252 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); | 4220 whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC); |
| 6253 } | 4221 } |
| 6254 } | 4222 } |
| 6255 #endif | 4223 #endif |
| 6256 /* Attempt to omit tables from the join that do not effect the result */ | 4224 /* Attempt to omit tables from the join that do not effect the result */ |
| 6257 if( pWInfo->nLevel>=2 | 4225 if( pWInfo->nLevel>=2 |
| 6258 && pResultSet!=0 | 4226 && pResultSet!=0 |
| 6259 && OptimizationEnabled(db, SQLITE_OmitNoopJoin) | 4227 && OptimizationEnabled(db, SQLITE_OmitNoopJoin) |
| 6260 ){ | 4228 ){ |
| 6261 Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet); | 4229 Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet); |
| 6262 if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy); | 4230 if( sWLB.pOrderBy ){ |
| 4231 tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy); |
| 4232 } |
| 6263 while( pWInfo->nLevel>=2 ){ | 4233 while( pWInfo->nLevel>=2 ){ |
| 6264 WhereTerm *pTerm, *pEnd; | 4234 WhereTerm *pTerm, *pEnd; |
| 6265 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; | 4235 pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop; |
| 6266 if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break; | 4236 if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break; |
| 6267 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 | 4237 if( (wctrlFlags & WHERE_WANT_DISTINCT)==0 |
| 6268 && (pLoop->wsFlags & WHERE_ONEROW)==0 | 4238 && (pLoop->wsFlags & WHERE_ONEROW)==0 |
| 6269 ){ | 4239 ){ |
| 6270 break; | 4240 break; |
| 6271 } | 4241 } |
| 6272 if( (tabUsed & pLoop->maskSelf)!=0 ) break; | 4242 if( (tabUsed & pLoop->maskSelf)!=0 ) break; |
| 6273 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; | 4243 pEnd = sWLB.pWC->a + sWLB.pWC->nTerm; |
| 6274 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ | 4244 for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){ |
| 6275 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 | 4245 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 |
| 6276 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) | 4246 && !ExprHasProperty(pTerm->pExpr, EP_FromJoin) |
| 6277 ){ | 4247 ){ |
| 6278 break; | 4248 break; |
| 6279 } | 4249 } |
| 6280 } | 4250 } |
| 6281 if( pTerm<pEnd ) break; | 4251 if( pTerm<pEnd ) break; |
| 6282 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId)); | 4252 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId)); |
| 6283 pWInfo->nLevel--; | 4253 pWInfo->nLevel--; |
| 6284 nTabList--; | 4254 nTabList--; |
| 6285 } | 4255 } |
| 6286 } | 4256 } |
| 6287 WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); | 4257 WHERETRACE(0xffff,("*** Optimizer Finished ***\n")); |
| 6288 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; | 4258 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut; |
| 6289 | 4259 |
| 6290 /* If the caller is an UPDATE or DELETE statement that is requesting | 4260 /* If the caller is an UPDATE or DELETE statement that is requesting |
| 6291 ** to use a one-pass algorithm, determine if this is appropriate. | 4261 ** to use a one-pass algorithm, determine if this is appropriate. |
| 6292 ** The one-pass algorithm only works if the WHERE clause constrains | 4262 ** The one-pass algorithm only works if the WHERE clause constrains |
| 6293 ** the statement to update a single row. | 4263 ** the statement to update or delete a single row. |
| 6294 */ | 4264 */ |
| 6295 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); | 4265 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); |
| 6296 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 | 4266 if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){ |
| 6297 && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){ | 4267 int wsFlags = pWInfo->a[0].pWLoop->wsFlags; |
| 6298 pWInfo->okOnePass = 1; | 4268 int bOnerow = (wsFlags & WHERE_ONEROW)!=0; |
| 6299 if( HasRowid(pTabList->a[0].pTab) ){ | 4269 if( bOnerow || ( (wctrlFlags & WHERE_ONEPASS_MULTIROW) |
| 6300 pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY; | 4270 && 0==(wsFlags & WHERE_VIRTUALTABLE) |
| 4271 )){ |
| 4272 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI; |
| 4273 if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){ |
| 4274 if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){ |
| 4275 bFordelete = OPFLAG_FORDELETE; |
| 4276 } |
| 4277 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY); |
| 4278 } |
| 6301 } | 4279 } |
| 6302 } | 4280 } |
| 6303 | 4281 |
| 6304 /* Open all tables in the pTabList and any indices selected for | 4282 /* Open all tables in the pTabList and any indices selected for |
| 6305 ** searching those tables. | 4283 ** searching those tables. |
| 6306 */ | 4284 */ |
| 6307 notReady = ~(Bitmask)0; | |
| 6308 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){ | 4285 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){ |
| 6309 Table *pTab; /* Table to open */ | 4286 Table *pTab; /* Table to open */ |
| 6310 int iDb; /* Index of database containing table/index */ | 4287 int iDb; /* Index of database containing table/index */ |
| 6311 struct SrcList_item *pTabItem; | 4288 struct SrcList_item *pTabItem; |
| 6312 | 4289 |
| 6313 pTabItem = &pTabList->a[pLevel->iFrom]; | 4290 pTabItem = &pTabList->a[pLevel->iFrom]; |
| 6314 pTab = pTabItem->pTab; | 4291 pTab = pTabItem->pTab; |
| 6315 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); | 4292 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); |
| 6316 pLoop = pLevel->pWLoop; | 4293 pLoop = pLevel->pWLoop; |
| 6317 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ | 4294 if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){ |
| 6318 /* Do nothing */ | 4295 /* Do nothing */ |
| 6319 }else | 4296 }else |
| 6320 #ifndef SQLITE_OMIT_VIRTUALTABLE | 4297 #ifndef SQLITE_OMIT_VIRTUALTABLE |
| 6321 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ | 4298 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){ |
| 6322 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); | 4299 const char *pVTab = (const char *)sqlite3GetVTable(db, pTab); |
| 6323 int iCur = pTabItem->iCursor; | 4300 int iCur = pTabItem->iCursor; |
| 6324 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); | 4301 sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB); |
| 6325 }else if( IsVirtual(pTab) ){ | 4302 }else if( IsVirtual(pTab) ){ |
| 6326 /* noop */ | 4303 /* noop */ |
| 6327 }else | 4304 }else |
| 6328 #endif | 4305 #endif |
| 6329 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 | 4306 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 |
| 6330 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){ | 4307 && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){ |
| 6331 int op = OP_OpenRead; | 4308 int op = OP_OpenRead; |
| 6332 if( pWInfo->okOnePass ){ | 4309 if( pWInfo->eOnePass!=ONEPASS_OFF ){ |
| 6333 op = OP_OpenWrite; | 4310 op = OP_OpenWrite; |
| 6334 pWInfo->aiCurOnePass[0] = pTabItem->iCursor; | 4311 pWInfo->aiCurOnePass[0] = pTabItem->iCursor; |
| 6335 }; | 4312 }; |
| 6336 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); | 4313 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); |
| 6337 assert( pTabItem->iCursor==pLevel->iTabCur ); | 4314 assert( pTabItem->iCursor==pLevel->iTabCur ); |
| 6338 testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 ); | 4315 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 ); |
| 6339 testcase( !pWInfo->okOnePass && pTab->nCol==BMS ); | 4316 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS ); |
| 6340 if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){ | 4317 if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){ |
| 6341 Bitmask b = pTabItem->colUsed; | 4318 Bitmask b = pTabItem->colUsed; |
| 6342 int n = 0; | 4319 int n = 0; |
| 6343 for(; b; b=b>>1, n++){} | 4320 for(; b; b=b>>1, n++){} |
| 6344 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, | 4321 sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, |
| 6345 SQLITE_INT_TO_PTR(n), P4_INT32); | 4322 SQLITE_INT_TO_PTR(n), P4_INT32); |
| 6346 assert( n<=pTab->nCol ); | 4323 assert( n<=pTab->nCol ); |
| 6347 } | 4324 } |
| 4325 #ifdef SQLITE_ENABLE_CURSOR_HINTS |
| 4326 if( pLoop->u.btree.pIndex!=0 ){ |
| 4327 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete); |
| 4328 }else |
| 4329 #endif |
| 4330 { |
| 4331 sqlite3VdbeChangeP5(v, bFordelete); |
| 4332 } |
| 4333 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK |
| 4334 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0, |
| 4335 (const u8*)&pTabItem->colUsed, P4_INT64); |
| 4336 #endif |
| 6348 }else{ | 4337 }else{ |
| 6349 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); | 4338 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); |
| 6350 } | 4339 } |
| 6351 if( pLoop->wsFlags & WHERE_INDEXED ){ | 4340 if( pLoop->wsFlags & WHERE_INDEXED ){ |
| 6352 Index *pIx = pLoop->u.btree.pIndex; | 4341 Index *pIx = pLoop->u.btree.pIndex; |
| 6353 int iIndexCur; | 4342 int iIndexCur; |
| 6354 int op = OP_OpenRead; | 4343 int op = OP_OpenRead; |
| 6355 /* iIdxCur is always set if to a positive value if ONEPASS is possible */ | 4344 /* iIdxCur is always set if to a positive value if ONEPASS is possible */ |
| 6356 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); | 4345 assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 ); |
| 6357 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) | 4346 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx) |
| 6358 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 | 4347 && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 |
| 6359 ){ | 4348 ){ |
| 6360 /* This is one term of an OR-optimization using the PRIMARY KEY of a | 4349 /* This is one term of an OR-optimization using the PRIMARY KEY of a |
| 6361 ** WITHOUT ROWID table. No need for a separate index */ | 4350 ** WITHOUT ROWID table. No need for a separate index */ |
| 6362 iIndexCur = pLevel->iTabCur; | 4351 iIndexCur = pLevel->iTabCur; |
| 6363 op = 0; | 4352 op = 0; |
| 6364 }else if( pWInfo->okOnePass ){ | 4353 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){ |
| 6365 Index *pJ = pTabItem->pTab->pIndex; | 4354 Index *pJ = pTabItem->pTab->pIndex; |
| 6366 iIndexCur = iIdxCur; | 4355 iIndexCur = iIdxCur; |
| 6367 assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); | 4356 assert( wctrlFlags & WHERE_ONEPASS_DESIRED ); |
| 6368 while( ALWAYS(pJ) && pJ!=pIx ){ | 4357 while( ALWAYS(pJ) && pJ!=pIx ){ |
| 6369 iIndexCur++; | 4358 iIndexCur++; |
| 6370 pJ = pJ->pNext; | 4359 pJ = pJ->pNext; |
| 6371 } | 4360 } |
| 6372 op = OP_OpenWrite; | 4361 op = OP_OpenWrite; |
| 6373 pWInfo->aiCurOnePass[1] = iIndexCur; | 4362 pWInfo->aiCurOnePass[1] = iIndexCur; |
| 6374 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){ | 4363 }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){ |
| 6375 iIndexCur = iIdxCur; | 4364 iIndexCur = iIdxCur; |
| 6376 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx; | 4365 if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx; |
| 6377 }else{ | 4366 }else{ |
| 6378 iIndexCur = pParse->nTab++; | 4367 iIndexCur = pParse->nTab++; |
| 6379 } | 4368 } |
| 6380 pLevel->iIdxCur = iIndexCur; | 4369 pLevel->iIdxCur = iIndexCur; |
| 6381 assert( pIx->pSchema==pTab->pSchema ); | 4370 assert( pIx->pSchema==pTab->pSchema ); |
| 6382 assert( iIndexCur>=0 ); | 4371 assert( iIndexCur>=0 ); |
| 6383 if( op ){ | 4372 if( op ){ |
| 6384 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); | 4373 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb); |
| 6385 sqlite3VdbeSetP4KeyInfo(pParse, pIx); | 4374 sqlite3VdbeSetP4KeyInfo(pParse, pIx); |
| 4375 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0 |
| 4376 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0 |
| 4377 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 |
| 4378 ){ |
| 4379 sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */ |
| 4380 } |
| 6386 VdbeComment((v, "%s", pIx->zName)); | 4381 VdbeComment((v, "%s", pIx->zName)); |
| 4382 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK |
| 4383 { |
| 4384 u64 colUsed = 0; |
| 4385 int ii, jj; |
| 4386 for(ii=0; ii<pIx->nColumn; ii++){ |
| 4387 jj = pIx->aiColumn[ii]; |
| 4388 if( jj<0 ) continue; |
| 4389 if( jj>63 ) jj = 63; |
| 4390 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue; |
| 4391 colUsed |= ((u64)1)<<(ii<63 ? ii : 63); |
| 4392 } |
| 4393 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0, |
| 4394 (u8*)&colUsed, P4_INT64); |
| 4395 } |
| 4396 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */ |
| 6387 } | 4397 } |
| 6388 } | 4398 } |
| 6389 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); | 4399 if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb); |
| 6390 notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor); | |
| 6391 } | 4400 } |
| 6392 pWInfo->iTop = sqlite3VdbeCurrentAddr(v); | 4401 pWInfo->iTop = sqlite3VdbeCurrentAddr(v); |
| 6393 if( db->mallocFailed ) goto whereBeginError; | 4402 if( db->mallocFailed ) goto whereBeginError; |
| 6394 | 4403 |
| 6395 /* Generate the code to do the search. Each iteration of the for | 4404 /* Generate the code to do the search. Each iteration of the for |
| 6396 ** loop below generates code for a single nested loop of the VM | 4405 ** loop below generates code for a single nested loop of the VM |
| 6397 ** program. | 4406 ** program. |
| 6398 */ | 4407 */ |
| 6399 notReady = ~(Bitmask)0; | 4408 notReady = ~(Bitmask)0; |
| 6400 for(ii=0; ii<nTabList; ii++){ | 4409 for(ii=0; ii<nTabList; ii++){ |
| 4410 int addrExplain; |
| 4411 int wsFlags; |
| 6401 pLevel = &pWInfo->a[ii]; | 4412 pLevel = &pWInfo->a[ii]; |
| 4413 wsFlags = pLevel->pWLoop->wsFlags; |
| 6402 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX | 4414 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX |
| 6403 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ | 4415 if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){ |
| 6404 constructAutomaticIndex(pParse, &pWInfo->sWC, | 4416 constructAutomaticIndex(pParse, &pWInfo->sWC, |
| 6405 &pTabList->a[pLevel->iFrom], notReady, pLevel); | 4417 &pTabList->a[pLevel->iFrom], notReady, pLevel); |
| 6406 if( db->mallocFailed ) goto whereBeginError; | 4418 if( db->mallocFailed ) goto whereBeginError; |
| 6407 } | 4419 } |
| 6408 #endif | 4420 #endif |
| 6409 explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags); | 4421 addrExplain = sqlite3WhereExplainOneScan( |
| 4422 pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags |
| 4423 ); |
| 6410 pLevel->addrBody = sqlite3VdbeCurrentAddr(v); | 4424 pLevel->addrBody = sqlite3VdbeCurrentAddr(v); |
| 6411 notReady = codeOneLoopStart(pWInfo, ii, notReady); | 4425 notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady); |
| 6412 pWInfo->iContinue = pLevel->addrCont; | 4426 pWInfo->iContinue = pLevel->addrCont; |
| 4427 if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){ |
| 4428 sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain); |
| 4429 } |
| 6413 } | 4430 } |
| 6414 | 4431 |
| 6415 /* Done. */ | 4432 /* Done. */ |
| 6416 VdbeModuleComment((v, "Begin WHERE-core")); | 4433 VdbeModuleComment((v, "Begin WHERE-core")); |
| 6417 return pWInfo; | 4434 return pWInfo; |
| 6418 | 4435 |
| 6419 /* Jump here if malloc fails */ | 4436 /* Jump here if malloc fails */ |
| 6420 whereBeginError: | 4437 whereBeginError: |
| 6421 if( pWInfo ){ | 4438 if( pWInfo ){ |
| 6422 pParse->nQueryLoop = pWInfo->savedNQueryLoop; | 4439 pParse->nQueryLoop = pWInfo->savedNQueryLoop; |
| (...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 6460 int j; | 4477 int j; |
| 6461 sqlite3VdbeResolveLabel(v, pLevel->addrNxt); | 4478 sqlite3VdbeResolveLabel(v, pLevel->addrNxt); |
| 6462 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ | 4479 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){ |
| 6463 sqlite3VdbeJumpHere(v, pIn->addrInTop+1); | 4480 sqlite3VdbeJumpHere(v, pIn->addrInTop+1); |
| 6464 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); | 4481 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop); |
| 6465 VdbeCoverage(v); | 4482 VdbeCoverage(v); |
| 6466 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen); | 4483 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen); |
| 6467 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen); | 4484 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen); |
| 6468 sqlite3VdbeJumpHere(v, pIn->addrInTop-1); | 4485 sqlite3VdbeJumpHere(v, pIn->addrInTop-1); |
| 6469 } | 4486 } |
| 6470 sqlite3DbFree(db, pLevel->u.in.aInLoop); | |
| 6471 } | 4487 } |
| 6472 sqlite3VdbeResolveLabel(v, pLevel->addrBrk); | 4488 sqlite3VdbeResolveLabel(v, pLevel->addrBrk); |
| 6473 if( pLevel->addrSkip ){ | 4489 if( pLevel->addrSkip ){ |
| 6474 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip); | 4490 sqlite3VdbeGoto(v, pLevel->addrSkip); |
| 6475 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); | 4491 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName)); |
| 6476 sqlite3VdbeJumpHere(v, pLevel->addrSkip); | 4492 sqlite3VdbeJumpHere(v, pLevel->addrSkip); |
| 6477 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); | 4493 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2); |
| 6478 } | 4494 } |
| 4495 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS |
| 4496 if( pLevel->addrLikeRep ){ |
| 4497 int op; |
| 4498 if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){ |
| 4499 op = OP_DecrJumpZero; |
| 4500 }else{ |
| 4501 op = OP_JumpZeroIncr; |
| 4502 } |
| 4503 sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep); |
| 4504 VdbeCoverage(v); |
| 4505 } |
| 4506 #endif |
| 6479 if( pLevel->iLeftJoin ){ | 4507 if( pLevel->iLeftJoin ){ |
| 6480 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); | 4508 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v); |
| 6481 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 | 4509 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 |
| 6482 || (pLoop->wsFlags & WHERE_INDEXED)!=0 ); | 4510 || (pLoop->wsFlags & WHERE_INDEXED)!=0 ); |
| 6483 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){ | 4511 if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){ |
| 6484 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); | 4512 sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); |
| 6485 } | 4513 } |
| 6486 if( pLoop->wsFlags & WHERE_INDEXED ){ | 4514 if( pLoop->wsFlags & WHERE_INDEXED ){ |
| 6487 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); | 4515 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); |
| 6488 } | 4516 } |
| 6489 if( pLevel->op==OP_Return ){ | 4517 if( pLevel->op==OP_Return ){ |
| 6490 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); | 4518 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst); |
| 6491 }else{ | 4519 }else{ |
| 6492 sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst); | 4520 sqlite3VdbeGoto(v, pLevel->addrFirst); |
| 6493 } | 4521 } |
| 6494 sqlite3VdbeJumpHere(v, addr); | 4522 sqlite3VdbeJumpHere(v, addr); |
| 6495 } | 4523 } |
| 6496 VdbeModuleComment((v, "End WHERE-loop%d: %s", i, | 4524 VdbeModuleComment((v, "End WHERE-loop%d: %s", i, |
| 6497 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); | 4525 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName)); |
| 6498 } | 4526 } |
| 6499 | 4527 |
| 6500 /* The "break" point is here, just past the end of the outer loop. | 4528 /* The "break" point is here, just past the end of the outer loop. |
| 6501 ** Set it. | 4529 ** Set it. |
| 6502 */ | 4530 */ |
| 6503 sqlite3VdbeResolveLabel(v, pWInfo->iBreak); | 4531 sqlite3VdbeResolveLabel(v, pWInfo->iBreak); |
| 6504 | 4532 |
| 6505 assert( pWInfo->nLevel<=pTabList->nSrc ); | 4533 assert( pWInfo->nLevel<=pTabList->nSrc ); |
| 6506 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){ | 4534 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){ |
| 6507 int k, last; | 4535 int k, last; |
| 6508 VdbeOp *pOp; | 4536 VdbeOp *pOp; |
| 6509 Index *pIdx = 0; | 4537 Index *pIdx = 0; |
| 6510 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; | 4538 struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; |
| 6511 Table *pTab = pTabItem->pTab; | 4539 Table *pTab = pTabItem->pTab; |
| 6512 assert( pTab!=0 ); | 4540 assert( pTab!=0 ); |
| 6513 pLoop = pLevel->pWLoop; | 4541 pLoop = pLevel->pWLoop; |
| 6514 | 4542 |
| 6515 /* For a co-routine, change all OP_Column references to the table of | 4543 /* For a co-routine, change all OP_Column references to the table of |
| 6516 ** the co-routine into OP_SCopy of result contained in a register. | 4544 ** the co-routine into OP_Copy of result contained in a register. |
| 6517 ** OP_Rowid becomes OP_Null. | 4545 ** OP_Rowid becomes OP_Null. |
| 6518 */ | 4546 */ |
| 6519 if( pTabItem->viaCoroutine && !db->mallocFailed ){ | 4547 if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){ |
| 6520 last = sqlite3VdbeCurrentAddr(v); | 4548 translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur, |
| 6521 k = pLevel->addrBody; | 4549 pTabItem->regResult, 0); |
| 6522 pOp = sqlite3VdbeGetOp(v, k); | |
| 6523 for(; k<last; k++, pOp++){ | |
| 6524 if( pOp->p1!=pLevel->iTabCur ) continue; | |
| 6525 if( pOp->opcode==OP_Column ){ | |
| 6526 pOp->opcode = OP_Copy; | |
| 6527 pOp->p1 = pOp->p2 + pTabItem->regResult; | |
| 6528 pOp->p2 = pOp->p3; | |
| 6529 pOp->p3 = 0; | |
| 6530 }else if( pOp->opcode==OP_Rowid ){ | |
| 6531 pOp->opcode = OP_Null; | |
| 6532 pOp->p1 = 0; | |
| 6533 pOp->p3 = 0; | |
| 6534 } | |
| 6535 } | |
| 6536 continue; | 4550 continue; |
| 6537 } | 4551 } |
| 6538 | 4552 |
| 6539 /* Close all of the cursors that were opened by sqlite3WhereBegin. | 4553 /* Close all of the cursors that were opened by sqlite3WhereBegin. |
| 6540 ** Except, do not close cursors that will be reused by the OR optimization | 4554 ** Except, do not close cursors that will be reused by the OR optimization |
| 6541 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors | 4555 ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors |
| 6542 ** created for the ONEPASS optimization. | 4556 ** created for the ONEPASS optimization. |
| 6543 */ | 4557 */ |
| 6544 if( (pTab->tabFlags & TF_Ephemeral)==0 | 4558 if( (pTab->tabFlags & TF_Ephemeral)==0 |
| 6545 && pTab->pSelect==0 | 4559 && pTab->pSelect==0 |
| 6546 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 | 4560 && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 |
| 6547 ){ | 4561 ){ |
| 6548 int ws = pLoop->wsFlags; | 4562 int ws = pLoop->wsFlags; |
| 6549 if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){ | 4563 if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){ |
| 6550 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); | 4564 sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); |
| 6551 } | 4565 } |
| 6552 if( (ws & WHERE_INDEXED)!=0 | 4566 if( (ws & WHERE_INDEXED)!=0 |
| 6553 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 | 4567 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 |
| 6554 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1] | 4568 && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1] |
| 6555 ){ | 4569 ){ |
| 6556 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); | 4570 sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); |
| 6557 } | 4571 } |
| 6558 } | 4572 } |
| 6559 | 4573 |
| 6560 /* If this scan uses an index, make VDBE code substitutions to read data | 4574 /* If this scan uses an index, make VDBE code substitutions to read data |
| 6561 ** from the index instead of from the table where possible. In some cases | 4575 ** from the index instead of from the table where possible. In some cases |
| 6562 ** this optimization prevents the table from ever being read, which can | 4576 ** this optimization prevents the table from ever being read, which can |
| 6563 ** yield a significant performance boost. | 4577 ** yield a significant performance boost. |
| 6564 ** | 4578 ** |
| 6565 ** Calls to the code generator in between sqlite3WhereBegin and | 4579 ** Calls to the code generator in between sqlite3WhereBegin and |
| 6566 ** sqlite3WhereEnd will have created code that references the table | 4580 ** sqlite3WhereEnd will have created code that references the table |
| 6567 ** directly. This loop scans all that code looking for opcodes | 4581 ** directly. This loop scans all that code looking for opcodes |
| 6568 ** that reference the table and converts them into opcodes that | 4582 ** that reference the table and converts them into opcodes that |
| 6569 ** reference the index. | 4583 ** reference the index. |
| 6570 */ | 4584 */ |
| 6571 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ | 4585 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){ |
| 6572 pIdx = pLoop->u.btree.pIndex; | 4586 pIdx = pLoop->u.btree.pIndex; |
| 6573 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ | 4587 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){ |
| 6574 pIdx = pLevel->u.pCovidx; | 4588 pIdx = pLevel->u.pCovidx; |
| 6575 } | 4589 } |
| 6576 if( pIdx && !db->mallocFailed ){ | 4590 if( pIdx |
| 4591 && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable)) |
| 4592 && !db->mallocFailed |
| 4593 ){ |
| 6577 last = sqlite3VdbeCurrentAddr(v); | 4594 last = sqlite3VdbeCurrentAddr(v); |
| 6578 k = pLevel->addrBody; | 4595 k = pLevel->addrBody; |
| 6579 pOp = sqlite3VdbeGetOp(v, k); | 4596 pOp = sqlite3VdbeGetOp(v, k); |
| 6580 for(; k<last; k++, pOp++){ | 4597 for(; k<last; k++, pOp++){ |
| 6581 if( pOp->p1!=pLevel->iTabCur ) continue; | 4598 if( pOp->p1!=pLevel->iTabCur ) continue; |
| 6582 if( pOp->opcode==OP_Column ){ | 4599 if( pOp->opcode==OP_Column ){ |
| 6583 int x = pOp->p2; | 4600 int x = pOp->p2; |
| 6584 assert( pIdx->pTable==pTab ); | 4601 assert( pIdx->pTable==pTab ); |
| 6585 if( !HasRowid(pTab) ){ | 4602 if( !HasRowid(pTab) ){ |
| 6586 Index *pPk = sqlite3PrimaryKeyIndex(pTab); | 4603 Index *pPk = sqlite3PrimaryKeyIndex(pTab); |
| 6587 x = pPk->aiColumn[x]; | 4604 x = pPk->aiColumn[x]; |
| 4605 assert( x>=0 ); |
| 6588 } | 4606 } |
| 6589 x = sqlite3ColumnOfIndex(pIdx, x); | 4607 x = sqlite3ColumnOfIndex(pIdx, x); |
| 6590 if( x>=0 ){ | 4608 if( x>=0 ){ |
| 6591 pOp->p2 = x; | 4609 pOp->p2 = x; |
| 6592 pOp->p1 = pLevel->iIdxCur; | 4610 pOp->p1 = pLevel->iIdxCur; |
| 6593 } | 4611 } |
| 6594 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 ); | 4612 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 ); |
| 6595 }else if( pOp->opcode==OP_Rowid ){ | 4613 }else if( pOp->opcode==OP_Rowid ){ |
| 6596 pOp->p1 = pLevel->iIdxCur; | 4614 pOp->p1 = pLevel->iIdxCur; |
| 6597 pOp->opcode = OP_IdxRowid; | 4615 pOp->opcode = OP_IdxRowid; |
| 6598 } | 4616 } |
| 6599 } | 4617 } |
| 6600 } | 4618 } |
| 6601 } | 4619 } |
| 6602 | 4620 |
| 6603 /* Final cleanup | 4621 /* Final cleanup |
| 6604 */ | 4622 */ |
| 6605 pParse->nQueryLoop = pWInfo->savedNQueryLoop; | 4623 pParse->nQueryLoop = pWInfo->savedNQueryLoop; |
| 6606 whereInfoFree(db, pWInfo); | 4624 whereInfoFree(db, pWInfo); |
| 6607 return; | 4625 return; |
| 6608 } | 4626 } |
| OLD | NEW |